import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/foundation.dart';
final screenHeight = 600;
final screenWidth = 600;
// 当前用户名（模拟数据）
String _currentUsername = "test@example.com";
String password = "password";

// 存储用户信息的列表
List<Map<String, String>> users = [
  {'email': _currentUsername, 'password': password},
];

void main() {
  runApp(const MyApp());
}

// 记账记录数据模型
class AccountRecord {
  final String id;
  final String type; // 'expense' 或 'income'
  final String category;
  final String description;
  final double amount;
  final DateTime date;
  final String method; // 'voice', 'image', 'manual'

  AccountRecord({
    required this.id,
    required this.type,
    required this.category,
    required this.description,
    required this.amount,
    required this.date,
    required this.method,
  });

  factory AccountRecord.fromJson(Map<String, dynamic> json) {
    return AccountRecord(
      id: json['id'] as String,
      type: json['type'] as String, // 'expense' 或 'income'
      category: json['category'] as String,
      description: json['description'] as String,
      amount: (json['amount'] as num).toDouble(),
      date: DateTime.parse(json['date']),
      method: json['method'] as String, // 'voice', 'image', 'manual'
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'type': type,
      'category': category,
      'description': description,
      'amount': amount,
      'date': date.toIso8601String(),
      'method': method,
    };
  }
}

List<AccountRecord> parseRecords(String responseBody) {
  final users = jsonDecode(responseBody) as List<dynamic>;

  // 查找指定ID的用户
  final userData = users.firstWhere(
    (user) => user['id'] == _currentUsername,
    orElse: () => null,
  );

  if (userData != null && userData.containsKey('accountRecord')) {
    final recordsJson = userData['accountRecord'] as List<dynamic>;
    return recordsJson
        .map<AccountRecord>((json) => AccountRecord.fromJson(json))
        .toList();
  } else {
    throw Exception('未找到用户: $_currentUsername');
  }
  // final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
  // return parsed
  //     .map<AccountRecord>((json) => AccountRecord.fromJson(json))
  //     .toList();
}

Future<List<AccountRecord>> fetchRecords() async {
  final response = await http.get(
    Uri.parse(
      'https://gitee.com/mobile-applications_1/accounting-app/raw/master/dataset/AccountRecord.json',
    ),
  );
  if (response.statusCode == 200) {
    return await compute(parseRecords, response.body);
  } else {
    throw Exception('Failed to load records');
  }
}


// 统计数据模型
class StatisticsData {
  final String period; // 年/月/日
  final double income;
  final double expense;
  final double balance;

  StatisticsData({
    required this.period,
    required this.income,
    required this.expense,
    required this.balance,
  });
}

// 分类统计数据模型
class CategoryData {
  final String category;
  final String categoryName;
  final double amount;
  final int count;

  CategoryData({
    required this.category,
    required this.categoryName,
    required this.amount,
    required this.count,
  });
}

// 预算数据模型
class Budget {
  final String id;
  final String category;
  final String categoryName;
  final double amount;
  final DateTime startDate;
  final DateTime endDate;
  final String period; // 'monthly', 'yearly'

  Budget({
    required this.id,
    required this.category,
    required this.categoryName,
    required this.amount,
    required this.startDate,
    required this.endDate,
    required this.period,
  });

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'category': category,
      'categoryName': categoryName,
      'amount': amount,
      'startDate': startDate.toIso8601String(),
      'endDate': endDate.toIso8601String(),
      'period': period,
    };
  }
  factory Budget.fromJson(Map<String, dynamic> json) {
    return Budget(
      id: json['id'] as String,
      category: json['category'] as String,
      categoryName: json['categoryName'] as String,
      amount: (json['amount'] as num).toDouble(), // 确保数值类型正确转换
      startDate: DateTime.parse(json['startDate'] as String),
      endDate: DateTime.parse(json['endDate'] as String),
      period: json['period'] as String,
    );
  }
}

// 预算使用情况数据模型
class BudgetUsage {
  final Budget budget;
  final double usedAmount;
  final double remainingAmount;
  final double percentage;
  final List<AccountRecord> relatedRecords;

  BudgetUsage({
    required this.budget,
    required this.usedAmount,
    required this.remainingAmount,
    required this.percentage,
    required this.relatedRecords,
  });
}

// 全局数据存储
class DataStorage {
  static final DataStorage _instance = DataStorage._internal();
  factory DataStorage() => _instance;
  DataStorage._internal();

  final List<AccountRecord> _records = [];
  final List<Budget> _budgets = [];

  List<AccountRecord> get records => List.unmodifiable(_records);
  List<Budget> get budgets => List.unmodifiable(_budgets);

// 添加备份数据存储字段
  String? backupDataString;
// 备份数据方法
  String backupData() {
    Map<String, dynamic> backup = {
      'records': _records.map((r) => r.toJson()).toList(),
      'budgets': _budgets.map((b) => b.toJson()).toList(),
    };
    String backupStr = jsonEncode(backup);
    // 保存到单例中
    backupDataString = backupStr;
    return jsonEncode(backup);
  }

  // 恢复数据方法
  void restoreData(String backupString) {
    Map<String, dynamic> backup = jsonDecode(backupString);
    
    _records.clear();
    _budgets.clear();
    
    for (var record in backup['records']) {
      _records.add(AccountRecord.fromJson(record));
    }
    
    for (var budget in backup['budgets']) {
      _budgets.add(Budget.fromJson(budget));
    }
  }

  void addRecord(AccountRecord record) {
    _records.add(record);
  }

  void removeRecord(String id) {
    _records.removeWhere((record) => record.id == id);
  }

  void updateRecord(AccountRecord updatedRecord) {
    final index = _records.indexWhere((record) => record.id == updatedRecord.id);
    if (index != -1) {
      _records[index] = updatedRecord;
    }
  }

  // 预算管理方法
  void addBudget(Budget budget) {
    _budgets.add(budget);
  }

  void removeBudget(String id) {
    _budgets.removeWhere((budget) => budget.id == id);
  }

  void updateBudget(Budget updatedBudget) {
    final index = _budgets.indexWhere((budget) => budget.id == updatedBudget.id);
    if (index != -1) {
      _budgets[index] = updatedBudget;
    }
  }

  // 添加测试数据
  void addTestData() async {
    final now = DateTime.now();
    final testRecords = await fetchRecords();
    // [
    //   // 支出数据
    //   AccountRecord(
    //     id: '1',
    //     type: 'expense',
    //     category: 'food',
    //     description: '午餐',
    //     amount: 35.0,
    //     date: now.subtract(const Duration(days: 1)),
    //     method: 'manual',
    //   ),
    //   AccountRecord(
    //     id: '2',
    //     type: 'expense',
    //     category: 'transport',
    //     description: '地铁费',
    //     amount: 6.0,
    //     date: now.subtract(const Duration(days: 2)),
    //     method: 'manual',
    //   ),
    //   AccountRecord(
    //     id: '3',
    //     type: 'expense',
    //     category: 'food',
    //     description: '晚餐',
    //     amount: 45.0,
    //     date: now.subtract(const Duration(days: 3)),
    //     method: 'manual',
    //   ),
    //   AccountRecord(
    //     id: '4',
    //     type: 'expense',
    //     category: 'entertainment',
    //     description: '电影票',
    //     amount: 68.0,
    //     date: now.subtract(const Duration(days: 5)),
    //     method: 'manual',
    //   ),
    //   AccountRecord(
    //     id: '5',
    //     type: 'expense',
    //     category: 'daily',
    //     description: '洗发水',
    //     amount: 29.0,
    //     date: now.subtract(const Duration(days: 7)),
    //     method: 'manual',
    //   ),
    //   AccountRecord(
    //     id: '6',
    //     type: 'expense',
    //     category: 'fixed',
    //     description: '房租',
    //     amount: 2500.0,
    //     date: now.subtract(const Duration(days: 10)),
    //     method: 'manual',
    //   ),
    //   // 收入数据
    //   AccountRecord(
    //     id: '7',
    //     type: 'income',
    //     category: 'salary',
    //     description: '工资',
    //     amount: 8000.0,
    //     date: now.subtract(const Duration(days: 15)),
    //     method: 'manual',
    //   ),
    //   AccountRecord(
    //     id: '8',
    //     type: 'income',
    //     category: 'parttime',
    //     description: '兼职收入',
    //     amount: 500.0,
    //     date: now.subtract(const Duration(days: 8)),
    //     method: 'manual',
    //   ),
    //   AccountRecord(
    //     id: '9',
    //     type: 'expense',
    //     category: 'family',
    //     description: '给父母生活费',
    //     amount: 1000.0,
    //     date: now.subtract(const Duration(days: 12)),
    //     method: 'manual',
    //   ),
    //   AccountRecord(
    //     id: '10',
    //     type: 'expense',
    //     category: 'food',
    //     description: '超市购物',
    //     amount: 158.0,
    //     date: now.subtract(const Duration(days: 4)),
    //     method: 'manual',
    //   ),
    //   // 添加今天的数据
    //   AccountRecord(
    //     id: '11',
    //     type: 'expense',
    //     category: 'food',
    //     description: '早餐',
    //     amount: 15.0,
    //     date: now,
    //     method: 'manual',
    //   ),
    //   AccountRecord(
    //     id: '12',
    //     type: 'income',
    //     category: 'other',
    //     description: '红包',
    //     amount: 100.0,
    //     date: now,
    //     method: 'manual',
    //   ),
    // ];

    _records.addAll(testRecords);
  }

  // 获取年度统计数据
  List<StatisticsData> getYearlyStatistics() {
    Map<int, List<AccountRecord>> yearGroups = {};

    for (var record in _records) {
      int year = record.date.year;
      yearGroups.putIfAbsent(year, () => []).add(record);
    }

    List<StatisticsData> result = [];
    List<int> sortedYears = yearGroups.keys.toList()..sort();

    for (int year in sortedYears) {
      double income = yearGroups[year]!
          .where((r) => r.type == 'income')
          .fold(0.0, (sum, r) => sum + r.amount);
      double expense = yearGroups[year]!
          .where((r) => r.type == 'expense')
          .fold(0.0, (sum, r) => sum + r.amount);

      result.add(StatisticsData(
        period: year.toString(),
        income: income,
        expense: expense,
        balance: income - expense,
      ));
    }

    return result;
  }

  // 获取月度统计数据（整年12个月）
  List<StatisticsData> getMonthlyStatistics(int year) {
    List<AccountRecord> yearRecords =
        _records.where((r) => r.date.year == year).toList();

    Map<int, List<AccountRecord>> monthGroups = {};

    for (var record in yearRecords) {
      int month = record.date.month;
      monthGroups.putIfAbsent(month, () => []).add(record);
    }

    List<StatisticsData> result = [];

    for (int month = 1; month <= 12; month++) {
      List<AccountRecord> monthRecords = monthGroups[month] ?? [];
      double income = monthRecords
          .where((r) => r.type == 'income')
          .fold(0.0, (sum, r) => sum + r.amount);
      double expense = monthRecords
          .where((r) => r.type == 'expense')
          .fold(0.0, (sum, r) => sum + r.amount);

      result.add(StatisticsData(
        period: '${month}月',
        income: income,
        expense: expense,
        balance: income - expense,
      ));
    }

    return result;
  }

  // 获取单个月的统计数据（按天统计）
  List<StatisticsData> getSingleMonthStatistics(int year, int month) {
    List<AccountRecord> monthRecords =
        _records
            .where((r) => r.date.year == year && r.date.month == month)
            .toList();

    Map<int, List<AccountRecord>> dayGroups = {};

    for (var record in monthRecords) {
      int day = record.date.day;
      dayGroups.putIfAbsent(day, () => []).add(record);
    }

    List<StatisticsData> result = [];
    DateTime firstDay = DateTime(year, month, 1);
    DateTime lastDay = DateTime(year, month + 1, 0);

    for (int day = 1; day <= lastDay.day; day++) {
      List<AccountRecord> dayRecords = dayGroups[day] ?? [];
      double income = dayRecords
          .where((r) => r.type == 'income')
          .fold(0.0, (sum, r) => sum + r.amount);
      double expense = dayRecords
          .where((r) => r.type == 'expense')
          .fold(0.0, (sum, r) => sum + r.amount);

      result.add(StatisticsData(
        period: '${day}日',
        income: income,
        expense: expense,
        balance: income - expense,
      ));
    }

    return result;
  }

  // 获取日统计数据
  List<StatisticsData> getDailyStatistics(int year, int month) {
    return getSingleMonthStatistics(year, month);
  }

  // 获取单日统计数据
  StatisticsData getSingleDayStatistics(DateTime date) {
    List<AccountRecord> dayRecords = _records
        .where((r) =>
    r.date.year == date.year &&
        r.date.month == date.month &&
        r.date.day == date.day)
        .toList();

    double income = dayRecords
        .where((r) => r.type == 'income')
        .fold(0.0, (sum, r) => sum + r.amount);
    double expense = dayRecords
        .where((r) => r.type == 'expense')
        .fold(0.0, (sum, r) => sum + r.amount);

    return StatisticsData(
      period: '${date.day}日',
      income: income,
      expense: expense,
      balance: income - expense,
    );
  }

  // 获取日期范围统计数据（用于日统计显示最近几天的数据）
  List<StatisticsData> getDateRangeStatistics(
    DateTime startDate,
    DateTime endDate,
  ) {
    List<StatisticsData> result = [];
    DateTime currentDate = startDate;

    while (currentDate.isBefore(endDate.add(const Duration(days: 1)))) {
      List<AccountRecord> dayRecords = _records
          .where((r) =>
      r.date.year == currentDate.year &&
          r.date.month == currentDate.month &&
          r.date.day == currentDate.day)
          .toList();

      double income = dayRecords
          .where((r) => r.type == 'income')
          .fold(0.0, (sum, r) => sum + r.amount);
      double expense = dayRecords
          .where((r) => r.type == 'expense')
          .fold(0.0, (sum, r) => sum + r.amount);

      result.add(
        StatisticsData(
          period: DateFormat('MM-dd').format(currentDate),
          income: income,
          expense: expense,
          balance: income - expense,
        ),
      );

      currentDate = currentDate.add(const Duration(days: 1));
    }

    return result;
  }

  // 获取分类统计数据
  List<CategoryData> getCategoryStatistics(
    String type,
    DateTime? startDate,
    DateTime? endDate,
  ) {
    List<AccountRecord> filteredRecords =
        _records
            .where((r) => r.type == type)
            .where(
              (r) =>
                  startDate == null ||
                  r.date.isAfter(startDate.subtract(const Duration(days: 1))),
            )
            .where(
              (r) =>
                  endDate == null ||
                  r.date.isBefore(endDate.add(const Duration(days: 1))),
            )
            .toList();

    Map<String, List<AccountRecord>> categoryGroups = {};

    for (var record in filteredRecords) {
      categoryGroups.putIfAbsent(record.category, () => []).add(record);
    }

    List<CategoryData> result = [];

    for (String category in categoryGroups.keys) {
      List<AccountRecord> categoryRecords = categoryGroups[category]!;
      double amount = categoryRecords.fold(0.0, (sum, r) => sum + r.amount);

      result.add(CategoryData(
        category: category,
        categoryName: _getCategoryName(category, type),
        amount: amount,
        count: categoryRecords.length,
      ));
    }

    result.sort((a, b) => b.amount.compareTo(a.amount));
    return result;
  }

  String _getCategoryName(String categoryId, String type) {
    final categories = type == 'expense'
        ? [
      {'id': 'fixed', 'name': '固定支出'},
      {'id': 'food', 'name': '日常饮食'},
      {'id': 'transport', 'name': '交通出行'},
      {'id': 'entertainment', 'name': '娱乐社交'},
      {'id': 'daily', 'name': '生活用品'},
      {'id': 'family', 'name': '家庭支出'},
      {'id': 'other', 'name': '其他'},
    ]
        : [
      {'id': 'salary', 'name': '工资'},
      {'id': 'parttime', 'name': '兼职'},
      {'id': 'investment', 'name': '理财'},
      {'id': 'other', 'name': '其他'},
    ];

    return categories.firstWhere(
          (cat) => cat['id'] == categoryId,
      orElse: () => {'name': '未知'},
    )['name'] as String;
  }

  // 获取预算使用情况
  List<BudgetUsage> getBudgetUsages() {
    List<BudgetUsage> usages = [];
    DateTime now = DateTime.now();

    for (Budget budget in _budgets) {
      // 获取预算期间内的相关记录
      List<AccountRecord> relatedRecords = _records
          .where((record) =>
              record.type == 'expense' &&
              record.category == budget.category &&
              record.date.isAfter(budget.startDate.subtract(const Duration(days: 1))) &&
              record.date.isBefore(budget.endDate.add(const Duration(days: 1))))
          .toList();

      double usedAmount = relatedRecords.fold(0.0, (sum, record) => sum + record.amount);
      double remainingAmount = budget.amount - usedAmount;
      double percentage = budget.amount > 0 ? (usedAmount / budget.amount) * 100 : 0;

      usages.add(BudgetUsage(
        budget: budget,
        usedAmount: usedAmount,
        remainingAmount: remainingAmount,
        percentage: percentage,
        relatedRecords: relatedRecords,
      ));
    }

    return usages;
  }

  // 获取当前月份的预算
  List<Budget> getCurrentMonthBudgets() {
    DateTime now = DateTime.now();
    return _budgets.where((budget) =>
        budget.period == 'monthly' &&
        budget.startDate.year == now.year &&
        budget.startDate.month == now.month).toList();
  }

  // 获取当前年份的预算
  List<Budget> getCurrentYearBudgets() {
    DateTime now = DateTime.now();
    return _budgets.where((budget) =>
        budget.period == 'yearly' &&
        budget.startDate.year == now.year).toList();
  }

  // 检查是否超出预算
  bool isBudgetExceeded(String category, String period) {
    List<BudgetUsage> usages = getBudgetUsages();
    BudgetUsage? usage = usages.cast<BudgetUsage?>().firstWhere(
      (usage) => usage?.budget.category == category && usage?.budget.period == period,
      orElse: () => null,
    );

    return usage != null && usage.percentage > 100;
  }

  // 添加测试预算数据
  void addTestBudgets() {
    DateTime now = DateTime.now();
    DateTime monthStart = DateTime(now.year, now.month, 1);
    DateTime monthEnd = DateTime(now.year, now.month + 1, 0);
    DateTime yearStart = DateTime(now.year, 1, 1);
    DateTime yearEnd = DateTime(now.year, 12, 31);

    final testBudgets = [
      Budget(
        id: 'budget_1',
        category: 'food',
        categoryName: '日常饮食',
        amount: 1000.0,
        startDate: monthStart,
        endDate: monthEnd,
        period: 'monthly',
      ),
      Budget(
        id: 'budget_2',
        category: 'transport',
        categoryName: '交通出行',
        amount: 300.0,
        startDate: monthStart,
        endDate: monthEnd,
        period: 'monthly',
      ),
      Budget(
        id: 'budget_3',
        category: 'entertainment',
        categoryName: '娱乐社交',
        amount: 500.0,
        startDate: monthStart,
        endDate: monthEnd,
        period: 'monthly',
      ),
      Budget(
        id: 'budget_4',
        category: 'daily',
        categoryName: '生活用品',
        amount: 200.0,
        startDate: monthStart,
        endDate: monthEnd,
        period: 'monthly',
      ),
      Budget(
        id: 'budget_5',
        category: 'fixed',
        categoryName: '固定支出',
        amount: 30000.0,
        startDate: yearStart,
        endDate: yearEnd,
        period: 'yearly',
      ),
    ];

    _budgets.addAll(testBudgets);
  }
}

final ValueNotifier<ThemeMode> themeNotifier = ValueNotifier(ThemeMode.light);

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<ThemeMode>(
      valueListenable: themeNotifier,
      builder: (_, mode, __) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Flutter 记账应用',
          theme: ThemeData.light(), // 浅色主题
          darkTheme: ThemeData.dark(), // 深色主题
          themeMode: mode, // 当前主题模式
          home: const LoginPage(),
        );
      },
    );
  }
}

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  bool _obscurePassword = true;
  String? _errorMessage;
  bool _isLoading = false;

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  Future<bool> _authenticateUser(String email, String password) async {
    await Future.delayed(const Duration(seconds: 1));
    for (var user in users) {
      if (user['email'] == email && user['password'] == password) {
        _currentUsername=email;
        return true;
      }
    }
    return false;
  }

  void _handleLogin() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

      final email = _emailController.text.trim();
      final password = _passwordController.text;

      final isAuthenticated = await _authenticateUser(email, password);

      setState(() {
        _isLoading = false;
      });

      if (isAuthenticated) {
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) => const MainPage()),
        );
      } else {
        setState(() {
          _errorMessage = '用户名或密码不正确';
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.symmetric(
            horizontal: screenWidth * 0.08,
            vertical: screenHeight * 0.05,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // 应用Logo和标题
              Center(
                child: Column(
                  children: [
                    Container(
                      width: screenWidth * 0.2,
                      height: screenWidth * 0.2,
                      decoration: BoxDecoration(
                        color: Colors.blue[100],
                        borderRadius: BorderRadius.circular(screenWidth * 0.05),
                      ),
                      child: Icon(
                        Icons.account_balance_wallet,
                        size: screenWidth * 0.1,
                        color: Colors.blue,
                      ),
                    ),
                    SizedBox(height: screenHeight * 0.03),
                    Text(
                      '智能记账',
                      style: TextStyle(
                        fontSize: screenWidth * 0.07,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: screenHeight * 0.01),
                    Text(
                      '请登录您的账户',
                      style: TextStyle(
                        fontSize: screenWidth * 0.04,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
              ),

              SizedBox(height: screenHeight * 0.06),

              // 登录表单
              Form(
                key: _formKey,
                child: Column(
                  children: [
                    // 邮箱输入
                    TextFormField(
                      controller: _emailController,
                      keyboardType: TextInputType.emailAddress,
                      style: TextStyle(fontSize: screenWidth * 0.04),
                      decoration: InputDecoration(
                        labelText: '邮箱',
                        labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                        prefixIcon: const Icon(Icons.email),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: screenWidth * 0.04,
                          vertical: screenHeight * 0.02,
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入邮箱';
                        }
                        if (!RegExp(
                          r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$',
                        ).hasMatch(value)) {
                          return '请输入有效的邮箱地址';
                        }
                        return null;
                      },
                    ),

                    SizedBox(height: screenHeight * 0.02),

                    // 密码输入
                    TextFormField(
                      controller: _passwordController,
                      obscureText: _obscurePassword,
                      style: TextStyle(fontSize: screenWidth * 0.04),
                      decoration: InputDecoration(
                        labelText: '密码',
                        labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                        prefixIcon: const Icon(Icons.lock),
                        suffixIcon: IconButton(
                          icon: Icon(
                            _obscurePassword
                                ? Icons.visibility
                                : Icons.visibility_off,
                          ),
                          onPressed: () {
                            setState(() {
                              _obscurePassword = !_obscurePassword;
                            });
                          },
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: screenWidth * 0.04,
                          vertical: screenHeight * 0.02,
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入密码';
                        }
                        if (value.length < 6) {
                          return '密码长度至少为6位';
                        }
                        return null;
                      },
                    ),

                    // 错误消息
                    if (_errorMessage != null)
                      Padding(
                        padding: EdgeInsets.only(top: screenHeight * 0.02),
                        child: Text(
                          _errorMessage!,
                          style: TextStyle(
                            color: Colors.red,
                            fontSize: screenWidth * 0.035,
                          ),
                        ),
                      ),

                    SizedBox(height: screenHeight * 0.03),

                    // 登录按钮
                    SizedBox(
                      width: double.infinity,
                      height: screenHeight * 0.06,
                      child: ElevatedButton(
                        onPressed: _isLoading ? null : _handleLogin,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                        ),
                        child: _isLoading
                            ? const CircularProgressIndicator(color: Colors.white)
                            : Text(
                          '登录',
                          style: TextStyle(
                            fontSize: screenWidth * 0.045,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              SizedBox(height: screenHeight * 0.03),

              // 忘记密码和注册选项
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  TextButton(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const ForgotPasswordPage(),
                        ),
                      );
                    },
                    child: Text(
                      '忘记密码?',
                      style: TextStyle(fontSize: screenWidth * 0.035),
                    ),
                  ),
                  TextButton(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const RegisterPage(),
                        ),
                      );
                    },
                    child: Text(
                      '注册账户',
                      style: TextStyle(fontSize: screenWidth * 0.035),
                    ),
                  ),
                ],
              ),

              SizedBox(height: screenHeight * 0.02),

              // 添加测试数据按钮
              Center(
                child: TextButton(
                  onPressed: () {
                    DataStorage().addTestData();
                    DataStorage().addTestBudgets();
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('测试数据和预算已添加，可以体验完整功能了！'),
                        backgroundColor: Colors.green,
                      ),
                    );
                  },
                  child: Text(
                    '添加测试数据 (用于体验统计功能)',
                    style: TextStyle(
                      fontSize: screenWidth * 0.032,
                      color: Colors.blue,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 注册页面
class RegisterPage extends StatefulWidget {
  const RegisterPage({Key? key}) : super(key: key);

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();
  String? _errorMessage;
  bool _isLoading = false;

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  void _handleRegister() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

      final email = _emailController.text.trim();
      final password = _passwordController.text;
      final confirmPassword = _confirmPasswordController.text;

      if (password != confirmPassword) {
        setState(() {
          _isLoading = false;
          _errorMessage = '两次输入的密码不一致';
        });
        return;
      }

      // 检查用户是否已存在
      for (var user in users) {
        if (user['email'] == email) {
          setState(() {
            _isLoading = false;
            _errorMessage = '该邮箱已被注册';
          });
          return;
        }
      }

      // 注册新用户
      users.add({'email': email, 'password': password});

      setState(() {
        _isLoading = false;
      });

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('注册成功，请使用新账户登录'),
          backgroundColor: Colors.green,
        ),
      );
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('注册账户')),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.symmetric(
            horizontal: screenWidth * 0.08,
            vertical: screenHeight * 0.05,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const Text('请输入您的邮箱和密码进行注册。', style: TextStyle(fontSize: 16)),
              const SizedBox(height: 20),
              Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      controller: _emailController,
                      keyboardType: TextInputType.emailAddress,
                      style: TextStyle(fontSize: screenWidth * 0.04),
                      decoration: InputDecoration(
                        labelText: '邮箱',
                        labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                        prefixIcon: const Icon(Icons.email),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: screenWidth * 0.04,
                          vertical: screenHeight * 0.02,
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入邮箱';
                        }
                        if (!RegExp(
                          r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$',
                        ).hasMatch(value)) {
                          return '请输入有效的邮箱地址';
                        }
                        return null;
                      },
                    ),
                    SizedBox(height: screenHeight * 0.02),
                    TextFormField(
                      controller: _passwordController,
                      obscureText: true,
                      style: TextStyle(fontSize: screenWidth * 0.04),
                      decoration: InputDecoration(
                        labelText: '密码',
                        labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                        prefixIcon: const Icon(Icons.lock),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: screenWidth * 0.04,
                          vertical: screenHeight * 0.02,
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入密码';
                        }
                        if (value.length < 6) {
                          return '密码长度至少为6位';
                        }
                        return null;
                      },
                    ),
                    SizedBox(height: screenHeight * 0.02),
                    TextFormField(
                      controller: _confirmPasswordController,
                      obscureText: true,
                      style: TextStyle(fontSize: screenWidth * 0.04),
                      decoration: InputDecoration(
                        labelText: '确认密码',
                        labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                        prefixIcon: const Icon(Icons.lock),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: screenWidth * 0.04,
                          vertical: screenHeight * 0.02,
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请再次输入密码';
                        }
                        return null;
                      },
                    ),
                    if (_errorMessage != null)
                      Padding(
                        padding: EdgeInsets.only(top: screenHeight * 0.02),
                        child: Text(
                          _errorMessage!,
                          style: TextStyle(
                            color: Colors.red,
                            fontSize: screenWidth * 0.035,
                          ),
                        ),
                      ),
                    const SizedBox(height: 20),
                    SizedBox(
                      width: double.infinity,
                      height: screenHeight * 0.06,
                      child: ElevatedButton(
                        onPressed: _isLoading ? null : _handleRegister,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                        ),
                        child:
                            _isLoading
                                ? const CircularProgressIndicator(
                                  color: Colors.white,
                                )
                                : Text(
                                  '注册',
                                  style: TextStyle(
                                    fontSize: screenWidth * 0.045,
                                    color: Colors.white,
                                  ),
                                ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 忘记密码功能
class ForgotPasswordPage extends StatefulWidget {
  const ForgotPasswordPage({super.key});

  @override
  _ForgotPasswordPageState createState() => _ForgotPasswordPageState();
}

class _ForgotPasswordPageState extends State<ForgotPasswordPage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _emailController = TextEditingController();
  String? _errorMessage;
  bool _isLoading = false;

  @override
  void dispose() {
    _emailController.dispose();
    super.dispose();
  }

  Future<void> _sendResetEmail(String email) async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    // 模拟发送重置密码邮件
    await Future.delayed(const Duration(seconds: 2));

    setState(() {
      _isLoading = false;
    });

    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('重置密码邮件已发送，请检查您的邮箱')));

    // 跳转到设置新密码界面
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => ResetPasswordPage(email: email)),
    );
  }

  void _handleForgotPassword() async {
    if (_formKey.currentState!.validate()) {
      final email = _emailController.text.trim();
      await _sendResetEmail(email);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('忘记密码')),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.symmetric(
            horizontal: screenWidth * 0.08,
            vertical: screenHeight * 0.05,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const Text(
                '请输入您注册时使用的邮箱，我们将发送重置密码的邮件给您。',
                style: TextStyle(fontSize: 16),
              ),
              const SizedBox(height: 20),
              Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      controller: _emailController,
                      keyboardType: TextInputType.emailAddress,
                      style: TextStyle(fontSize: screenWidth * 0.04),
                      decoration: InputDecoration(
                        labelText: '邮箱',
                        labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                        prefixIcon: const Icon(Icons.email),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: screenWidth * 0.04,
                          vertical: screenHeight * 0.02,
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入邮箱';
                        }
                        if (!RegExp(
                          r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$',
                        ).hasMatch(value)) {
                          return '请输入有效的邮箱地址';
                        }
                        return null;
                      },
                    ),
                    if (_errorMessage != null)
                      Padding(
                        padding: EdgeInsets.only(top: screenHeight * 0.02),
                        child: Text(
                          _errorMessage!,
                          style: TextStyle(
                            color: Colors.red,
                            fontSize: screenWidth * 0.035,
                          ),
                        ),
                      ),
                    const SizedBox(height: 20),
                    SizedBox(
                      width: double.infinity,
                      height: screenHeight * 0.06,
                      child: ElevatedButton(
                        onPressed: _isLoading ? null : _handleForgotPassword,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                        ),
                        child:
                            _isLoading
                                ? const CircularProgressIndicator(
                                  color: Colors.white,
                                )
                                : Text(
                                  '发送重置邮件',
                                  style: TextStyle(
                                    fontSize: screenWidth * 0.045,
                                    color: Colors.white,
                                  ),
                                ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 重置密码界面
class ResetPasswordPage extends StatefulWidget {
  final String email;

  const ResetPasswordPage({Key? key, required this.email}) : super(key: key);

  @override
  _ResetPasswordPageState createState() => _ResetPasswordPageState();
}

class _ResetPasswordPageState extends State<ResetPasswordPage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _newPasswordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();
  final TextEditingController _verificationCodeController =
      TextEditingController();
  String? _errorMessage;
  bool _isLoading = false;
  String verificationCode = '1234'; // 模拟验证码

  @override
  void dispose() {
    _newPasswordController.dispose();
    _confirmPasswordController.dispose();
    _verificationCodeController.dispose();
    super.dispose();
  }

  void _handleResetPassword() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

      final newPassword = _newPasswordController.text;
      final confirmPassword = _confirmPasswordController.text;
      final inputCode = _verificationCodeController.text;

      if (newPassword != confirmPassword) {
        setState(() {
          _isLoading = false;
          _errorMessage = '两次输入的密码不一致';
        });
        return;
      }

      if (inputCode != verificationCode) {
        setState(() {
          _isLoading = false;
          _errorMessage = '验证码不正确';
        });
        return;
      }

      // 更新用户密码
      for (var i = 0; i < users.length; i++) {
        if (users[i]['email'] == widget.email) {
          users[i]['password'] = newPassword;
          break;
        }
      }

      setState(() {
        _isLoading = false;
      });

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('密码重置成功，请使用新密码登录'),
          backgroundColor: Colors.green,
        ),
      );
      Navigator.of(context).popUntil((route) => route.isFirst);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('重置密码')),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.symmetric(
            horizontal: screenWidth * 0.08,
            vertical: screenHeight * 0.05,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const Text(
                '请输入新密码、确认新密码和验证码来重置您的密码。',
                style: TextStyle(fontSize: 16),
              ),
              const SizedBox(height: 20),
              Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      controller: _newPasswordController,
                      obscureText: true,
                      style: TextStyle(fontSize: screenWidth * 0.04),
                      decoration: InputDecoration(
                        labelText: '新密码',
                        labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                        prefixIcon: const Icon(Icons.lock),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: screenWidth * 0.04,
                          vertical: screenHeight * 0.02,
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入新密码';
                        }
                        if (value.length < 6) {
                          return '密码长度至少为6位';
                        }
                        return null;
                      },
                    ),
                    SizedBox(height: screenHeight * 0.02),
                    TextFormField(
                      controller: _confirmPasswordController,
                      obscureText: true,
                      style: TextStyle(fontSize: screenWidth * 0.04),
                      decoration: InputDecoration(
                        labelText: '确认新密码',
                        labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                        prefixIcon: const Icon(Icons.lock),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: screenWidth * 0.04,
                          vertical: screenHeight * 0.02,
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请再次输入新密码';
                        }
                        return null;
                      },
                    ),
                    SizedBox(height: screenHeight * 0.02),
                    Row(
                      children: [
                        Expanded(
                          child: TextFormField(
                            controller: _verificationCodeController,
                            style: TextStyle(fontSize: screenWidth * 0.04),
                            decoration: InputDecoration(
                              labelText: '验证码',
                              labelStyle: TextStyle(
                                fontSize: screenWidth * 0.035,
                              ),
                              prefixIcon: const Icon(Icons.security),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(10.0),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: screenWidth * 0.04,
                                vertical: screenHeight * 0.02,
                              ),
                            ),
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return '请输入验证码';
                              }
                              return null;
                            },
                          ),
                        ),
                        SizedBox(width: screenWidth * 0.02),
                        Text(
                          verificationCode,
                          style: TextStyle(fontSize: screenWidth * 0.04),
                        ),
                      ],
                    ),
                    if (_errorMessage != null)
                      Padding(
                        padding: EdgeInsets.only(top: screenHeight * 0.02),
                        child: Text(
                          _errorMessage!,
                          style: TextStyle(
                            color: Colors.red,
                            fontSize: screenWidth * 0.035,
                          ),
                        ),
                      ),
                    const SizedBox(height: 20),
                    SizedBox(
                      width: double.infinity,
                      height: screenHeight * 0.06,
                      child: ElevatedButton(
                        onPressed: _isLoading ? null : _handleResetPassword,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                        ),
                        child:
                            _isLoading
                                ? const CircularProgressIndicator(
                                  color: Colors.white,
                                )
                                : Text(
                                  '重置密码',
                                  style: TextStyle(
                                    fontSize: screenWidth * 0.045,
                                    color: Colors.white,
                                  ),
                                ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  int _currentIndex = 0;

  final List<Widget> _pages = [
    const AccountPage(),
    const BillPage(),
    const FriendsPage(), // 替换原来的StatisticsPage
    const ProfilePage(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('智能记账', style: TextStyle(fontSize: screenWidth * 0.045)),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.logout),
            onPressed: () {
              Navigator.of(context).pushReplacement(
                MaterialPageRoute(builder: (context) => const LoginPage()),
              );
            },
          ),
        ],
      ),
      body: _pages[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        selectedItemColor: Colors.blue,
        unselectedItemColor: Colors.grey,
        selectedFontSize: screenWidth * 0.03,
        unselectedFontSize: screenWidth * 0.028,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.account_balance_wallet),
            label: '记账',
          ),
          BottomNavigationBarItem(icon: Icon(Icons.receipt), label: '账单'),
          BottomNavigationBarItem(
            icon: Icon(Icons.people), // 改为好友图标
            label: '好友', // 改为好友
          ),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'),
        ],
      ),
    );
  }
}

// 记账页面
class AccountPage extends StatelessWidget {
  const AccountPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '选择记账方式',
            style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 32.0),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _buildRecordingMethod(
                  context,
                  icon: Icons.mic,
                  title: '语音记账',
                  subtitle: '说话即可快速记录',
                  color: Colors.green,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const VoiceRecordingPage(),
                      ),
                    );
                  },
                ),
                _buildRecordingMethod(
                  context,
                  icon: Icons.camera_alt,
                  title: '图片记账',
                  subtitle: '拍照或上传图片识别',
                  color: Colors.orange,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const ImageRecordingPage(),
                      ),
                    );
                  },
                ),
                _buildRecordingMethod(
                  context,
                  icon: Icons.edit,
                  title: '手动记账',
                  subtitle: '手动输入详细信息',
                  color: Colors.blue,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const ManualRecordingPage(),
                      ),
                    );
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRecordingMethod(
      BuildContext context, {
        required IconData icon,
        required String title,
        required String subtitle,
        required Color color,
        required VoidCallback onTap,
      }) {
    return Card(
      elevation: 4.0,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8.0),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Row(
            children: [
              Container(
                width: 40.0,
                height: 120.0,
                decoration: BoxDecoration(
                  color: color.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8.0),
                ),
                child: Icon(icon, size: 20.0, color: color),
              ),
              const SizedBox(width: 16.0),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      title,
                      style: const TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4.0),
                    Text(
                      subtitle,
                      style: const TextStyle(
                        fontSize: 12.0,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
              ),
              const Icon(
                Icons.arrow_forward_ios,
                color: Colors.grey,
                size: 16.0,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 语音记账页面
class VoiceRecordingPage extends StatefulWidget {
  const VoiceRecordingPage({Key? key}) : super(key: key);

  @override
  _VoiceRecordingPageState createState() => _VoiceRecordingPageState();
}

class _VoiceRecordingPageState extends State<VoiceRecordingPage> {
  bool _isRecording = false;
  bool _hasPermission = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('语音记账', style: TextStyle(fontSize: screenWidth * 0.045)),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: Padding(
        padding: EdgeInsets.all(screenWidth * 0.06),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '请按住说话转文字记账',
              style: TextStyle(fontSize: screenWidth * 0.045),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: screenHeight * 0.06),

            GestureDetector(
              onTapDown: (_) => _startRecording(),
              onTapUp: (_) => _stopRecording(),
              onTapCancel: () => _stopRecording(),
              child: Container(
                width: screenWidth * 0.4,
                height: screenWidth * 0.4,
                decoration: BoxDecoration(
                  color:
                      _isRecording
                          ? Colors.red.withOpacity(0.3)
                          : Colors.blue.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(screenWidth * 0.2),
                  border: Border.all(
                    color: _isRecording ? Colors.red : Colors.blue,
                    width: 3.0,
                  ),
                ),
                child: Icon(
                  Icons.mic,
                  size: screenWidth * 0.15,
                  color: _isRecording ? Colors.red : Colors.blue,
                ),
              ),
            ),

            SizedBox(height: screenHeight * 0.03),

            if (!_hasPermission) ...[
              Text(
                '允许访问麦克风权限',
                style: TextStyle(
                  fontSize: screenWidth * 0.035,
                  color: Colors.grey,
                ),
              ),
              SizedBox(height: screenHeight * 0.02),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Checkbox(
                    value: _hasPermission,
                    onChanged: (value) {
                      setState(() {
                        _hasPermission = value ?? false;
                      });
                    },
                  ),
                  Text(
                    '同意访问权限',
                    style: TextStyle(fontSize: screenWidth * 0.035),
                  ),
                ],
              ),
            ],

            if (_isRecording)
              Text(
                '正在录音...',
                style: TextStyle(
                  fontSize: screenWidth * 0.04,
                  color: Colors.red,
                ),
              ),
          ],
        ),
      ),
    );
  }

  void _startRecording() {
    if (_hasPermission) {
      setState(() {
        _isRecording = true;
      });
    } else {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('请先允许麦克风权限')));
    }
  }

  void _stopRecording() {
    setState(() {
      _isRecording = false;
    });
    if (_hasPermission) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('语音识别功能尚未实现')));
    }
  }
}

// 图片记账页面
class ImageRecordingPage extends StatelessWidget {
  const ImageRecordingPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('图片记账'), backgroundColor: Colors.blue),
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '选择图片记账方式',
              style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 32.0),
            Expanded(
              child: ListView(
                children: [
                  _buildImageMethod(
                    context,
                    icon: Icons.videocam,
                    title: '录屏识别',
                    subtitle: '录制屏幕内容进行识别',
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const ScreenRecordingPage(),
                        ),
                      );
                    },
                  ),
                  const SizedBox(height: 16.0),
                  _buildImageMethod(
                    context,
                    icon: Icons.photo,
                    title: '图片识别',
                    subtitle: '上传账单截图进行识别',
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const ImageUploadPage(),
                        ),
                      );
                    },
                  ),
                  const SizedBox(height: 16.0),
                  _buildImageMethod(
                    context,
                    icon: Icons.camera_alt,
                    title: '实物记录',
                    subtitle: '拍摄实物照片进行记录',
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const PhotoTakingPage(),
                        ),
                      );
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildImageMethod(
      BuildContext context, {
        required IconData icon,
        required String title,
        required String subtitle,
        required VoidCallback onTap,
      }) {
    return Card(
      elevation: 2.0,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8.0),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Row(
            children: [
              Container(
                width: 50.0,
                height: 50.0,
                decoration: BoxDecoration(
                  color: Colors.orange.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8.0),
                ),
                child: Icon(icon, size: 24.0, color: Colors.orange),
              ),
              const SizedBox(width: 16.0),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: const TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4.0),
                    Text(
                      subtitle,
                      style: const TextStyle(
                        fontSize: 14.0,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
              ),
              const Icon(
                Icons.arrow_forward_ios,
                color: Colors.grey,
                size: 16.0,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 录屏识别页面
class ScreenRecordingPage extends StatefulWidget {
  const ScreenRecordingPage({Key? key}) : super(key: key);

  @override
  _ScreenRecordingPageState createState() => _ScreenRecordingPageState();
}

class _ScreenRecordingPageState extends State<ScreenRecordingPage> {
  bool _hasPermission = false;
  bool _isRecording = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('录屏识别'), backgroundColor: Colors.blue),
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              '请开启录屏权限并进行录屏',
              style: TextStyle(fontSize: 18.0),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24.0),

            if (!_hasPermission) ...[
              const Text(
                '允许访问存储空间和相机权限',
                style: TextStyle(fontSize: 12.0, color: Colors.grey),
              ),
              const SizedBox(height: 16.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Checkbox(
                    value: _hasPermission,
                    onChanged: (value) {
                      setState(() {
                        _hasPermission = value ?? false;
                      });
                    },
                  ),
                  const Text('同意访问权限'),
                ],
              ),
              const SizedBox(height: 32.0),
            ],

            if (_hasPermission) ...[
              GestureDetector(
                onTap: _toggleRecording,
                child: Container(
                  width: 120.0,
                  height: 120.0,
                  decoration: BoxDecoration(
                    color:
                    _isRecording
                        ? Colors.red.withOpacity(0.1)
                        : Colors.blue.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(60.0),
                    border: Border.all(
                      color: _isRecording ? Colors.red : Colors.blue,
                      width: 3.0,
                    ),
                  ),
                  child: Icon(
                    _isRecording ? Icons.stop : Icons.videocam,
                    size: 48.0,
                    color: _isRecording ? Colors.red : Colors.blue,
                  ),
                ),
              ),
              const SizedBox(height: 16.0),
              Text(
                _isRecording ? '点击停止录屏' : '开始录屏',
                style: const TextStyle(fontSize: 16.0),
              ),
            ],
          ],
        ),
      ),
    );
  }

  void _toggleRecording() {
    setState(() {
      _isRecording = !_isRecording;
    });

    if (_isRecording) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('开始录屏...')));
    } else {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('录屏已停止，识别功能尚未实现')));
    }
  }
}

// 图片上传页面
class ImageUploadPage extends StatefulWidget {
  const ImageUploadPage({Key? key}) : super(key: key);

  @override
  _ImageUploadPageState createState() => _ImageUploadPageState();
}

class _ImageUploadPageState extends State<ImageUploadPage> {
  bool _hasPermission = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('图片识别'), backgroundColor: Colors.blue),
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              '请上传账单截图',
              style: TextStyle(fontSize: 18.0),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24.0),

            if (!_hasPermission) ...[
              const Text(
                '允许访问存储空间和相机权限',
                style: TextStyle(fontSize: 12.0, color: Colors.grey),
              ),
              const SizedBox(height: 16.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Checkbox(
                    value: _hasPermission,
                    onChanged: (value) {
                      setState(() {
                        _hasPermission = value ?? false;
                      });
                    },
                  ),
                  const Text('同意访问权限'),
                ],
              ),
              const SizedBox(height: 32.0),
            ],

            if (_hasPermission) ...[
              GestureDetector(
                onTap: _selectImage,
                child: Container(
                  width: 120.0,
                  height: 120.0,
                  decoration: BoxDecoration(
                    color: Colors.blue.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12.0),
                    border: Border.all(
                      color: Colors.blue,
                      width: 2.0,
                      style: BorderStyle.solid,
                    ),
                  ),
                  child: const Icon(
                    Icons.add_a_photo,
                    size: 48.0,
                    color: Colors.blue,
                  ),
                ),
              ),
              const SizedBox(height: 16.0),
              const Text('选择图片上传', style: TextStyle(fontSize: 16.0)),
            ],
          ],
        ),
      ),
    );
  }

  void _selectImage() {
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('图片选择和识别功能尚未实现')));
  }
}

// 拍照页面
class PhotoTakingPage extends StatefulWidget {
  const PhotoTakingPage({Key? key}) : super(key: key);

  @override
  _PhotoTakingPageState createState() => _PhotoTakingPageState();
}

class _PhotoTakingPageState extends State<PhotoTakingPage> {
  bool _hasPermission = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('实物记录'), backgroundColor: Colors.blue),
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              '请打开相机拍照',
              style: TextStyle(fontSize: 18.0),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24.0),

            if (!_hasPermission) ...[
              const Text(
                '允许访问存储空间和相机权限',
                style: TextStyle(fontSize: 12.0, color: Colors.grey),
              ),
              const SizedBox(height: 16.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Checkbox(
                    value: _hasPermission,
                    onChanged: (value) {
                      setState(() {
                        _hasPermission = value ?? false;
                      });
                    },
                  ),
                  const Text('同意访问权限'),
                ],
              ),
              const SizedBox(height: 32.0),
            ],

            if (_hasPermission) ...[
              GestureDetector(
                onTap: _takePhoto,
                child: Container(
                  width: 120.0,
                  height: 120.0,
                  decoration: BoxDecoration(
                    color: Colors.blue.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(60.0),
                    border: Border.all(color: Colors.blue, width: 3.0),
                  ),
                  child: const Icon(
                    Icons.camera_alt,
                    size: 48.0,
                    color: Colors.blue,
                  ),
                ),
              ),
              const SizedBox(height: 16.0),
              const Text('请开始拍照', style: TextStyle(fontSize: 16.0)),
            ],
          ],
        ),
      ),
    );
  }

  void _takePhoto() {
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('相机拍照功能尚未实现')));
  }
}

// 手动记账页面
class ManualRecordingPage extends StatefulWidget {
  const ManualRecordingPage({Key? key}) : super(key: key);

  @override
  _ManualRecordingPageState createState() => _ManualRecordingPageState();
}

class _ManualRecordingPageState extends State<ManualRecordingPage> {
  String _selectedType = 'expense';
  String? _selectedCategory;

  final List<Map<String, dynamic>> _expenseCategories = [
    {'id': 'fixed', 'name': '固定支出', 'icon': Icons.home},
    {'id': 'food', 'name': '日常饮食', 'icon': Icons.restaurant},
    {'id': 'transport', 'name': '交通出行', 'icon': Icons.directions_car},
    {'id': 'entertainment', 'name': '娱乐社交', 'icon': Icons.sports_esports},
    {'id': 'daily', 'name': '生活用品', 'icon': Icons.shopping_cart},
    {'id': 'family', 'name': '家庭支出', 'icon': Icons.family_restroom},
    {'id': 'other', 'name': '其他', 'icon': Icons.more_horiz},
  ];

  final List<Map<String, dynamic>> _incomeCategories = [
    {'id': 'salary', 'name': '工资', 'icon': Icons.work},
    {'id': 'parttime', 'name': '兼职', 'icon': Icons.schedule},
    {'id': 'investment', 'name': '理财', 'icon': Icons.trending_up},
    {'id': 'other', 'name': '其他', 'icon': Icons.more_horiz},
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('手动记账', style: TextStyle(fontSize: screenWidth * 0.045)),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: Column(
        children: [
          // 顶部切换按钮
          Container(
            margin: EdgeInsets.all(screenWidth * 0.04),
            decoration: BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.circular(25.0),
            ),
            child: Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        _selectedType = 'expense';
                        _selectedCategory = null;
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        vertical: screenHeight * 0.015,
                      ),
                      decoration: BoxDecoration(
                        color:
                            _selectedType == 'expense'
                                ? Colors.red
                                : Colors.transparent,
                        borderRadius: BorderRadius.circular(25.0),
                      ),
                      child: Text(
                        '支出',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: screenWidth * 0.04,
                          color:
                              _selectedType == 'expense'
                                  ? Colors.white
                                  : Colors.black,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        _selectedType = 'income';
                        _selectedCategory = null;
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        vertical: screenHeight * 0.015,
                      ),
                      decoration: BoxDecoration(
                        color:
                            _selectedType == 'income'
                                ? Colors.green
                                : Colors.transparent,
                        borderRadius: BorderRadius.circular(25.0),
                      ),
                      child: Text(
                        '收入',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: screenWidth * 0.04,
                          color:
                              _selectedType == 'income'
                                  ? Colors.white
                                  : Colors.black,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          // 分类选择区域
          Expanded(
            child: Padding(
              padding: EdgeInsets.symmetric(
                horizontal: screenWidth * 0.04,
                vertical: screenHeight * 0.01,
              ),
              child:
                  _selectedType == 'expense'
                      ? _buildExpenseCategories()
                      : _buildIncomeCategories(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildExpenseCategories() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children:
          _expenseCategories
              .map((category) => _buildCategoryRow(category))
              .toList(),
    );
  }

  Widget _buildIncomeCategories() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children:
          _incomeCategories
              .map((category) => _buildCategoryRow(category))
              .toList(),
    );
  }

  Widget _buildCategoryRow(Map<String, dynamic> category) {
    return Container(
      width: double.infinity,
      height: screenHeight * (_selectedType == 'expense' ? 0.08 : 0.12),
      margin: EdgeInsets.symmetric(vertical: screenHeight * 0.005),
      child: Card(
        elevation: 2.0,
        child: InkWell(
          onTap: () {
            setState(() {
              _selectedCategory = category['id'];
            });
            _showRecordForm(context, category);
          },
          borderRadius: BorderRadius.circular(8.0),
          child: Padding(
            padding: EdgeInsets.symmetric(
              horizontal: screenWidth * 0.04,
              vertical: screenHeight * 0.01,
            ),
            child: Row(
              children: [
                Container(
                  width: screenWidth * 0.12,
                  height: screenWidth * 0.12,
                  decoration: BoxDecoration(
                    color: (_selectedType == 'expense'
                            ? Colors.red
                            : Colors.green)
                        .withOpacity(0.1),
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                  child: Icon(
                    category['icon'],
                    size: screenWidth * 0.07,
                    color:
                        _selectedType == 'expense' ? Colors.red : Colors.green,
                  ),
                ),
                SizedBox(width: screenWidth * 0.04),
                Expanded(
                  child: Text(
                    category['name'],
                    style: TextStyle(
                      fontSize: screenWidth * 0.04,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Icon(
                  Icons.arrow_forward_ios,
                  color: Colors.grey,
                  size: screenWidth * 0.04,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _showRecordForm(BuildContext context, Map<String, dynamic> category) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder:
            (context) =>
                RecordFormPage(type: _selectedType, category: category),
      ),
    );
  }
}

// 记录表单页面
class RecordFormPage extends StatefulWidget {
  final String type;
  final Map<String, dynamic> category;

  const RecordFormPage({Key? key, required this.type, required this.category})
    : super(key: key);

  @override
  _RecordFormPageState createState() => _RecordFormPageState();
}

class _RecordFormPageState extends State<RecordFormPage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _descriptionController = TextEditingController();
  final TextEditingController _amountController = TextEditingController();
  DateTime _selectedDate = DateTime.now();

  @override
  void dispose() {
    _descriptionController.dispose();
    _amountController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '${widget.category['name']} - ${widget.type == 'expense' ? '支出' : '收入'}',
          style: TextStyle(fontSize: screenWidth * 0.04),
        ),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: Padding(
        padding: EdgeInsets.all(screenWidth * 0.04),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 分类显示
              Card(
                child: Padding(
                  padding: EdgeInsets.all(screenWidth * 0.04),
                  child: Row(
                    children: [
                      Icon(
                        widget.category['icon'],
                        size: screenWidth * 0.08,
                        color:
                            widget.type == 'expense'
                                ? Colors.red
                                : Colors.green,
                      ),
                      SizedBox(width: screenWidth * 0.04),
                      Text(
                        widget.category['name'],
                        style: TextStyle(
                          fontSize: screenWidth * 0.045,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              SizedBox(height: screenHeight * 0.03),

              // 消费备注
              TextFormField(
                controller: _descriptionController,
                style: TextStyle(fontSize: screenWidth * 0.04),
                decoration: InputDecoration(
                  labelText: '消费备注',
                  labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                  border: const OutlineInputBorder(),
                  prefixIcon: const Icon(Icons.description),
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: screenWidth * 0.04,
                    vertical: screenHeight * 0.02,
                  ),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入备注';
                  }
                  return null;
                },
              ),

              SizedBox(height: screenHeight * 0.02),

              // 金额
              TextFormField(
                controller: _amountController,
                keyboardType: TextInputType.number,
                style: TextStyle(fontSize: screenWidth * 0.04),
                decoration: InputDecoration(
                  labelText: '金额',
                  labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                  border: const OutlineInputBorder(),
                  prefixIcon: const Icon(Icons.attach_money),
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: screenWidth * 0.04,
                    vertical: screenHeight * 0.02,
                  ),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入金额';
                  }
                  if (double.tryParse(value) == null) {
                    return '请输入有效金额';
                  }
                  return null;
                },
              ),

              SizedBox(height: screenHeight * 0.02),

              // 日期选择
              InkWell(
                onTap: _selectDate,
                child: InputDecorator(
                  decoration: InputDecoration(
                    labelText: '消费时间',
                    labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                    border: const OutlineInputBorder(),
                    prefixIcon: const Icon(Icons.calendar_today),
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: screenWidth * 0.04,
                      vertical: screenHeight * 0.02,
                    ),
                  ),
                  child: Text(
                    DateFormat('yyyy-MM-dd').format(_selectedDate),
                    style: TextStyle(fontSize: screenWidth * 0.04),
                  ),
                ),
              ),

              SizedBox(height: screenHeight * 0.04),

              // 保存按钮
              SizedBox(
                width: double.infinity,
                height: screenHeight * 0.06,
                child: ElevatedButton(
                  onPressed: _saveRecord,
                  style: ElevatedButton.styleFrom(
                    backgroundColor:
                        widget.type == 'expense' ? Colors.red : Colors.green,
                  ),
                  child: Text(
                    '保存${widget.type == 'expense' ? '支出' : '收入'}记录',
                    style: TextStyle(
                      fontSize: screenWidth * 0.04,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
    );
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  void _saveRecord() {
    if (_formKey.currentState!.validate()) {
      final record = AccountRecord(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        type: widget.type,
        category: widget.category['id'],
        description: _descriptionController.text,
        amount: double.parse(_amountController.text),
        date: _selectedDate,
        method: 'manual',
      );

      DataStorage().addRecord(record);

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('${widget.type == 'expense' ? '支出' : '收入'}记录已保存'),
          backgroundColor: widget.type == 'expense' ? Colors.red : Colors.green,
        ),
      );

      Navigator.pop(context);
    }
  }
}

// 账单页面（修改后，添加统计功能按钮）
class BillPage extends StatefulWidget {
  const BillPage({Key? key}) : super(key: key);

  @override
  _BillPageState createState() => _BillPageState();
}

class _BillPageState extends State<BillPage> {
  @override
  Widget build(BuildContext context) {
    final records = DataStorage().records;

    if (records.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.receipt, size: screenWidth * 0.2, color: Colors.grey),
            SizedBox(height: screenHeight * 0.03),
            Text(
              '暂无账单记录',
              style: TextStyle(
                fontSize: screenWidth * 0.045,
                color: Colors.grey,
              ),
            ),
            SizedBox(height: screenHeight * 0.01),
            Text(
              '快去记录您的第一笔账单吧！',
              style: TextStyle(
                fontSize: screenWidth * 0.035,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    // 计算总收入和支出
    double totalIncome = records
        .where((r) => r.type == 'income')
        .fold(0.0, (sum, r) => sum + r.amount);
    double totalExpense = records
        .where((r) => r.type == 'expense')
        .fold(0.0, (sum, r) => sum + r.amount);

    return Column(
      children: [
        // 统计卡片
        Container(
          margin: EdgeInsets.all(screenWidth * 0.04),
          child: Row(
            children: [
              Expanded(
                child: Card(
                  color: Colors.green[50],
                  child: Padding(
                    padding: EdgeInsets.all(screenWidth * 0.04),
                    child: Column(
                      children: [
                        const Icon(Icons.trending_up, color: Colors.green),
                        SizedBox(height: screenHeight * 0.01),
                        Text(
                          '总收入',
                          style: TextStyle(
                            color: Colors.green,
                            fontSize: screenWidth * 0.035,
                          ),
                        ),
                        Text(
                          '¥${totalIncome.toStringAsFixed(2)}',
                          style: TextStyle(
                            fontSize: screenWidth * 0.045,
                            fontWeight: FontWeight.bold,
                            color: Colors.green,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              Expanded(
                child: Card(
                  color: Colors.red[50],
                  child: Padding(
                    padding: EdgeInsets.all(screenWidth * 0.04),
                    child: Column(
                      children: [
                        const Icon(Icons.trending_down, color: Colors.red),
                        SizedBox(height: screenHeight * 0.01),
                        Text(
                          '总支出',
                          style: TextStyle(
                            color: Colors.red,
                            fontSize: screenWidth * 0.035,
                          ),
                        ),
                        Text(
                          '¥${totalExpense.toStringAsFixed(2)}',
                          style: TextStyle(
                            fontSize: screenWidth * 0.045,
                            fontWeight: FontWeight.bold,
                            color: Colors.red,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),

        // 添加统计功能按钮
        Container(
          margin: EdgeInsets.symmetric(horizontal: screenWidth * 0.04),
          child: SizedBox(
            width: double.infinity,
            height: screenHeight * 0.06,
            child: ElevatedButton.icon(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const StatisticsPage(),
                  ),
                );
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
              ),
              icon: const Icon(Icons.bar_chart, color: Colors.white),
              label: Text(
                '查看详细统计分析',
                style: TextStyle(
                  fontSize: screenWidth * 0.04,
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),

        SizedBox(height: screenHeight * 0.02),

        // 记录列表
        Expanded(
          child: ListView.builder(
            padding: EdgeInsets.symmetric(horizontal: screenWidth * 0.04),
            itemCount: records.length,
            itemBuilder: (context, index) {
              final record = records[records.length - 1 - index]; // 倒序显示
              return Card(
                margin: EdgeInsets.only(bottom: screenHeight * 0.01),
                child: ListTile(
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: screenWidth * 0.04,
                    vertical: screenHeight * 0.005,
                  ),
                  leading: CircleAvatar(
                    backgroundColor:
                        record.type == 'expense'
                            ? Colors.red[100]
                            : Colors.green[100],
                    child: Icon(
                      record.type == 'expense' ? Icons.remove : Icons.add,
                      color:
                          record.type == 'expense' ? Colors.red : Colors.green,
                    ),
                  ),
                  title: Text(
                    record.description,
                    style: TextStyle(fontSize: screenWidth * 0.04),
                  ),
                  subtitle: Text(
                    '${_getCategoryName(record.category, record.type)} • ${DateFormat('MM-dd').format(record.date)}',
                    style: TextStyle(fontSize: screenWidth * 0.032),
                  ),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        '${record.type == 'expense' ? '-' : '+'}¥${record.amount.toStringAsFixed(2)}',
                        style: TextStyle(
                          fontSize: screenWidth * 0.04,
                          fontWeight: FontWeight.bold,
                          color: record.type == 'expense' ? Colors.red : Colors.green,
                        ),
                      ),
                      IconButton(
                        icon: Icon(Icons.edit, color: Colors.blue),
                        onPressed: () async {
                          // 跳转到编辑页面
                          await Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => EditRecordPage(record: record),
                            ),
                          );
                          setState(() {}); // 返回后刷新
                        },
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  String _getCategoryName(String categoryId, String type) {
    final categories = type == 'expense'
        ? [
      {'id': 'fixed', 'name': '固定支出'},
      {'id': 'food', 'name': '日常饮食'},
      {'id': 'transport', 'name': '交通出行'},
      {'id': 'entertainment', 'name': '娱乐社交'},
      {'id': 'daily', 'name': '生活用品'},
      {'id': 'family', 'name': '家庭支出'},
      {'id': 'other', 'name': '其他'},
    ]
        : [
      {'id': 'salary', 'name': '工资'},
      {'id': 'parttime', 'name': '兼职'},
      {'id': 'investment', 'name': '理财'},
      {'id': 'other', 'name': '其他'},
    ];

    return categories.firstWhere(
          (cat) => cat['id'] == categoryId,
      orElse: () => {'name': '未知'},
    )['name'] as String;
  }
}

//好友界面
class FriendsPage extends StatefulWidget {
  const FriendsPage({Key? key}) : super(key: key);

  @override
  _FriendsPageState createState() => _FriendsPageState();
}

class _FriendsPageState extends State<FriendsPage> {
  List<Map<String, dynamic>> _friends = []; // 好友列表
  List<Map<String, dynamic>> _feed = []; // 好友动态列表
  final TextEditingController _friendUsernameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 初始化好友列表和动态数据
    _friends = [
      {'id': 1, 'username': 'friend1@example.com', 'status': '在线'},
      {'id': 2, 'username': 'friend2@example.com', 'status': '离线'},
      {'id': 3, 'username': 'friend3@example.com', 'status': '在线'},
    ];

    _feed = [
      {
        'id': 1,
        'username': 'friend1@example.com',
        'action': '添加了支出记录：午餐 ¥35',
        'timestamp': '2023-10-01 12:00'
      },
      {
        'id': 2,
        'username': 'friend2@example.com',
        'action': '分享了账单：9月支出总结',
        'timestamp': '2023-10-01 11:30'
      },
      {
        'id': 3,
        'username': 'friend3@example.com',
        'action': '添加了收入记录：工资 ¥8000',
        'timestamp': '2023-10-01 10:00'
      },
    ];
  }

  @override
  void dispose() {
    _friendUsernameController.dispose();
    super.dispose();
  }

  void _addFriend() {
    final username = _friendUsernameController.text.trim();
    if (username.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入好友用户名')),
      );
      return;
    }

    if (_friends.any((friend) => friend['username'] == username)) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('该好友已存在')),
      );
      return;
    }

    setState(() {
      _friends.add({
        'id': _friends.length + 1,
        'username': username,
        'status': '在线',
      });
    });

    _friendUsernameController.clear();
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('已添加好友: $username')),
    );
  }

  void _navigateToFeed() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => FriendsFeedPage(feed: _feed),
      ),
    );
  }

  void _navigateToShareBill() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ShareBillPage(friends: _friends),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '好友功能',
          style: TextStyle(fontSize: screenWidth * 0.045),
        ),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: Column(
        children: [
          // 添加好友区域
          Padding(
            padding: EdgeInsets.all(screenWidth * 0.04),
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _friendUsernameController,
                        decoration: InputDecoration(
                          labelText: '输入好友用户名',
                          border: const OutlineInputBorder(),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: screenWidth * 0.04,
                            vertical: screenHeight * 0.015,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: screenWidth * 0.02),
                    ElevatedButton(
                      onPressed: _addFriend,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                      ),
                      child: Text(
                        '添加好友',
                        style: TextStyle(
                          fontSize: screenWidth * 0.035,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

          // 好友列表
          Expanded(
            child: _friends.isEmpty
                ? Center(
              child: Text(
                '暂无好友',
                style: TextStyle(
                  fontSize: screenWidth * 0.04,
                  color: Colors.grey,
                ),
              ),
            )
                : ListView.builder(
              itemCount: _friends.length,
              itemBuilder: (context, index) {
                final friend = _friends[index];
                return Card(
                  margin: EdgeInsets.symmetric(
                    horizontal: screenWidth * 0.04,
                    vertical: screenHeight * 0.01,
                  ),
                  child: ListTile(
                    leading: CircleAvatar(
                      backgroundColor: Colors.blue,
                      child: Text(
                        friend['username'][0], // 显示用户名首字母
                        style: const TextStyle(color: Colors.white),
                      ),
                    ),
                    title: Text(
                      friend['username'],
                      style: TextStyle(
                        fontSize: screenWidth * 0.04,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    subtitle: Text(
                      '状态: ${friend['status']}',
                      style: TextStyle(
                        fontSize: screenWidth * 0.032,
                        color: Colors.grey,
                      ),
                    ),
                    trailing: IconButton(
                      icon: const Icon(Icons.message),
                      color: Colors.blue,
                      onPressed: () {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text('与 ${friend['username']} 聊天功能尚未实现'),
                          ),
                        );
                      },
                    ),
                  ),
                );
              },
            ),
          ),

          // 底部功能按钮
          Container(
            margin: EdgeInsets.symmetric(horizontal: screenWidth * 0.04, vertical: screenHeight * 0.02),
            child: Column(
              children: [
                _buildFriendFeature(context, '好友动态', Icons.timeline, _navigateToFeed),
                SizedBox(height: screenHeight * 0.02),
                _buildFriendFeature(context, '账单分享', Icons.share, _navigateToShareBill),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFriendFeature(BuildContext context, String title, IconData icon, VoidCallback onPressed) {
    return SizedBox(
      width: double.infinity,
      height: screenHeight * 0.06,
      child: ElevatedButton.icon(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.blue,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25),
          ),
        ),
        icon: Icon(icon, color: Colors.white),
        label: Text(
          title,
          style: TextStyle(fontSize: screenWidth * 0.04, color: Colors.white),
        ),
      ),
    );
  }
}

// 好友动态页面
class FriendsFeedPage extends StatelessWidget {
  final List<Map<String, dynamic>> feed;

  const FriendsFeedPage({Key? key, required this.feed}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '好友动态',
          style: TextStyle(fontSize: screenWidth * 0.045),
        ),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: feed.isEmpty
          ? Center(
        child: Text(
          '暂无好友动态',
          style: TextStyle(
            fontSize: screenWidth * 0.04,
            color: Colors.grey,
          ),
        ),
      )
          : ListView.builder(
        itemCount: feed.length,
        itemBuilder: (context, index) {
          final dynamicItem = feed[index];
          return Card(
            margin: EdgeInsets.symmetric(
              horizontal: screenWidth * 0.04,
              vertical: screenHeight * 0.01,
            ),
            child: ListTile(
              leading: CircleAvatar(
                backgroundColor: Colors.blue,
                child: Text(
                  dynamicItem['username'][0],
                  style: const TextStyle(color: Colors.white),
                ),
              ),
              title: Text(
                dynamicItem['username'],
                style: TextStyle(
                  fontSize: screenWidth * 0.04,
                  fontWeight: FontWeight.bold,
                ),
              ),
              subtitle: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    dynamicItem['action'],
                    style: TextStyle(
                      fontSize: screenWidth * 0.035,
                      color: Colors.black,
                    ),
                  ),
                  SizedBox(height: screenHeight * 0.005),
                  Text(
                    dynamicItem['timestamp'],
                    style: TextStyle(
                      fontSize: screenWidth * 0.03,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

// 账单分享页面
class ShareBillPage extends StatefulWidget {
  final List<Map<String, dynamic>> friends;

  const ShareBillPage({Key? key, required this.friends}) : super(key: key);

  @override
  _ShareBillPageState createState() => _ShareBillPageState();
}

class _ShareBillPageState extends State<ShareBillPage> {
  List<Map<String, dynamic>> _selectedFriends = [];

  void _toggleFriendSelection(Map<String, dynamic> friend) {
    setState(() {
      if (_selectedFriends.contains(friend)) {
        _selectedFriends.remove(friend);
      } else {
        _selectedFriends.add(friend);
      }
    });
  }

  void _shareBill() {
    if (_selectedFriends.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请选择至少一个好友')),
      );
      return;
    }

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('已分享账单给 ${_selectedFriends.map((f) => f['username']).join(', ')}'),
      ),
    );

    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
        title: Text(
        '分享账单',
        style: TextStyle(fontSize: screenWidth * 0.045),
    ),
    backgroundColor: Colors.blue,
    foregroundColor: Colors.white,
    ),
      body: Column(
        children: [
          Padding(
            padding: EdgeInsets.all(screenWidth * 0.04),
            child: Text(
              '选择要分享的好友：',
              style: TextStyle(
                fontSize: screenWidth * 0.04,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: widget.friends.length,
              itemBuilder: (context, index) {
                final friend = widget.friends[index];
                final isSelected = _selectedFriends.contains(friend);

                return Card(
                  margin: EdgeInsets.symmetric(
                    horizontal: screenWidth * 0.04,
                    vertical: screenHeight * 0.01,
                  ),
                  child: ListTile(
                    leading: CircleAvatar(
                      backgroundColor: Colors.blue,
                      child: Text(
                        friend['username'][0],
                        style: const TextStyle(color: Colors.white),
                      ),
                    ),
                    title: Text(
                      friend['username'],
                      style: TextStyle(
                        fontSize: screenWidth * 0.04,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    subtitle: Text(
                      '状态: ${friend['status']}',
                      style: TextStyle(
                        fontSize: screenWidth * 0.032,
                        color: Colors.grey,
                      ),
                    ),
                    trailing: Checkbox(
                      value: isSelected,
                      onChanged: (value) {
                        _toggleFriendSelection(friend);
                      },
                    ),
                  ),
                );
              },
            ),
          ),
          SizedBox(height: screenHeight * 0.02),
          // 分享按钮
          Padding(
            padding: EdgeInsets.symmetric(horizontal: screenWidth * 0.04),
            child: SizedBox(
              width: double.infinity,
              height: screenHeight * 0.06,
              child: ElevatedButton(
                onPressed: _shareBill,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                ),
                child: Text(
                  '分享账单',
                  style: TextStyle(
                    fontSize: screenWidth * 0.04,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}


// 统计页面（保持原有功能不变，只是访问方式改变）
class StatisticsPage extends StatefulWidget {
  const StatisticsPage({Key? key}) : super(key: key);

  @override
  _StatisticsPageState createState() => _StatisticsPageState();
}

class _StatisticsPageState extends State<StatisticsPage>
    with TickerProviderStateMixin {
  late TabController _tabController;
  String _selectedPeriod = 'month'; // year, month, day
  int _selectedYear = DateTime.now().year;
  int _selectedMonth = DateTime.now().month;
  int _selectedDay = DateTime.now().day;
  DateTime _selectedDate = DateTime.now();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('统计分析', style: TextStyle(fontSize: screenWidth * 0.045)),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: Column(
        children: [
          // 时间选择器
          Container(
            padding: EdgeInsets.all(screenWidth * 0.04),
            color: Colors.blue[50],
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '数据统计分析',
                  style: TextStyle(
                    fontSize: screenWidth * 0.045,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Row(
                  children: [
                    _buildPeriodButton('年', 'year'),
                    SizedBox(width: screenWidth * 0.02),
                    _buildPeriodButton('月', 'month'),
                    SizedBox(width: screenWidth * 0.02),
                    _buildPeriodButton('日', 'day'),
                  ],
                ),
              ],
            ),
          ),

          // 年月日选择
          Container(
            padding: EdgeInsets.symmetric(
              horizontal: screenWidth * 0.04,
              vertical: screenHeight * 0.01,
            ),
            child: Column(
              children: [
                // 年月选择行
                Row(
                  children: [
                    Expanded(
                      child: DropdownButton<int>(
                        value: _selectedYear,
                        isExpanded: true,
                        items: List.generate(10, (index) {
                          int year = DateTime.now().year - index;
                          return DropdownMenuItem(
                            value: year,
                            child: Text('${year}年'),
                          );
                        }),
                        onChanged: (value) {
                          setState(() {
                            _selectedYear = value!;
                            _updateSelectedDate();
                          });
                        },
                      ),
                    ),
                    if (_selectedPeriod == 'month' ||
                        _selectedPeriod == 'day') ...[
                      SizedBox(width: screenWidth * 0.04),
                      Expanded(
                        child: DropdownButton<int>(
                          value: _selectedMonth,
                          isExpanded: true,
                          items: List.generate(12, (index) {
                            int month = index + 1;
                            return DropdownMenuItem(
                              value: month,
                              child: Text('${month}月'),
                            );
                          }),
                          onChanged: (value) {
                            setState(() {
                              _selectedMonth = value!;
                              _updateSelectedDate();
                            });
                          },
                        ),
                      ),
                    ],
                  ],
                ),

                // 日期选择（仅在选择日统计时显示）
                if (_selectedPeriod == 'day') ...[
                  SizedBox(height: screenHeight * 0.01),
                  Row(
                    children: [
                      Expanded(
                        child: InkWell(
                          onTap: _selectSpecificDate,
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: screenWidth * 0.04,
                              vertical: screenHeight * 0.015,
                            ),
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  DateFormat(
                                    'yyyy年MM月dd日',
                                  ).format(_selectedDate),
                                  style: TextStyle(
                                    fontSize: screenWidth * 0.035,
                                  ),
                                ),
                                Icon(
                                  Icons.calendar_today,
                                  size: screenWidth * 0.04,
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ],
            ),
          ),

          // TabBar
          TabBar(
            controller: _tabController,
            labelColor: Colors.blue,
            unselectedLabelColor: Colors.grey,
            labelStyle: TextStyle(fontSize: screenWidth * 0.035),
            tabs: const [
              Tab(text: '趋势图表'),
              Tab(text: '分类统计'),
              Tab(text: '饼图分析'),
            ],
          ),

          // TabBarView
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildTrendChart(),
                _buildCategoryStatistics(),
                _buildPieChartAnalysis(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPeriodButton(String text, String period) {
    bool isSelected = _selectedPeriod == period;

    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedPeriod = period;
          _updateSelectedDate();
        });
      },
      child: Container(
        padding: EdgeInsets.symmetric(
          horizontal: screenWidth * 0.03,
          vertical: screenWidth * 0.015,
        ),
        decoration: BoxDecoration(
          color: isSelected ? Colors.blue : Colors.white,
          borderRadius: BorderRadius.circular(15),
          border: Border.all(color: Colors.blue),
        ),
        child: Text(
          text,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.blue,
            fontSize: screenWidth * 0.032,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

  // 更新选中的日期
  void _updateSelectedDate() {
    _selectedDate = DateTime(_selectedYear, _selectedMonth, _selectedDay);
    // 确保选中的日期是有效的
    if (_selectedDate.month != _selectedMonth) {
      // 如果日期无效（比如2月30日），则设置为该月的最后一天
      _selectedDate = DateTime(_selectedYear, _selectedMonth + 1, 0);
      _selectedDay = _selectedDate.day;
    }
  }

  // 选择具体日期
  Future<void> _selectSpecificDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
    );
    if (picked != null) {
      setState(() {
        _selectedDate = picked;
        _selectedYear = picked.year;
        _selectedMonth = picked.month;
        _selectedDay = picked.day;
      });
    }
  }

  // 趋势图表
  Widget _buildTrendChart() {
    List<StatisticsData> data;

    switch (_selectedPeriod) {
      case 'year':
        data = DataStorage().getYearlyStatistics();
        break;
      case 'month':
        data = DataStorage().getMonthlyStatistics(_selectedYear);
        break;
      case 'day':
      // 显示选中日期前后7天的数据
        DateTime startDate = _selectedDate.subtract(const Duration(days: 7));
        DateTime endDate = _selectedDate.add(const Duration(days: 7));
        data = DataStorage().getDateRangeStatistics(startDate, endDate);
        break;
      default:
        data = [];
    }

    if (data.isEmpty || data.every((d) => d.income == 0 && d.expense == 0)) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.bar_chart, size: screenWidth * 0.15, color: Colors.grey),
            SizedBox(height: screenHeight * 0.02),
            Text(
              '暂无数据',
              style: TextStyle(
                fontSize: screenWidth * 0.04,
                color: Colors.grey,
              ),
            ),
            if (_selectedPeriod == 'day')
              Padding(
                padding: EdgeInsets.only(top: screenHeight * 0.01),
                child: Text(
                  '显示 ${DateFormat('MM-dd').format(_selectedDate.subtract(const Duration(days: 7)))} 至 ${DateFormat('MM-dd').format(_selectedDate.add(const Duration(days: 7)))} 的数据',
                  style: TextStyle(
                    fontSize: screenWidth * 0.032,
                    color: Colors.grey,
                  ),
                ),
              ),
          ],
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.all(screenWidth * 0.04),
      child: Column(
        children: [
          // 统计摘要
          Card(
            child: Padding(
              padding: EdgeInsets.all(screenWidth * 0.04),
              child: Column(
                children: [
                  // 显示时间范围
                  if (_selectedPeriod == 'day')
                    Padding(
                      padding: EdgeInsets.only(bottom: screenHeight * 0.02),
                      child: Text(
                        '时间范围：${DateFormat('MM月dd日').format(_selectedDate.subtract(const Duration(days: 7)))} - ${DateFormat('MM月dd日').format(_selectedDate.add(const Duration(days: 7)))}',
                        style: TextStyle(
                          fontSize: screenWidth * 0.035,
                          color: Colors.grey[600],
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Column(
                        children: [
                          Text(
                            '总收入',
                            style: TextStyle(
                              fontSize: screenWidth * 0.035,
                              color: Colors.green,
                            ),
                          ),
                          Text(
                            '¥${data.fold(0.0, (sum, d) => sum + d.income).toStringAsFixed(2)}',
                            style: TextStyle(
                              fontSize: screenWidth * 0.04,
                              fontWeight: FontWeight.bold,
                              color: Colors.green,
                            ),
                          ),
                        ],
                      ),
                      Column(
                        children: [
                          Text(
                            '总支出',
                            style: TextStyle(
                              fontSize: screenWidth * 0.035,
                              color: Colors.red,
                            ),
                          ),
                          Text(
                            '¥${data.fold(0.0, (sum, d) => sum + d.expense).toStringAsFixed(2)}',
                            style: TextStyle(
                              fontSize: screenWidth * 0.04,
                              fontWeight: FontWeight.bold,
                              color: Colors.red,
                            ),
                          ),
                        ],
                      ),
                      Column(
                        children: [
                          Text(
                            '净收入',
                            style: TextStyle(
                              fontSize: screenWidth * 0.035,
                              color: Colors.blue,
                            ),
                          ),
                          Text(
                            '¥${data.fold(0.0, (sum, d) => sum + d.balance).toStringAsFixed(2)}',
                            style: TextStyle(
                              fontSize: screenWidth * 0.04,
                              fontWeight: FontWeight.bold,
                              color: Colors.blue,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),

          SizedBox(height: screenHeight * 0.02),

          // 图表显示
          Expanded(
            child: Card(
              child: Padding(
                padding: EdgeInsets.all(screenWidth * 0.04),
                child: Column(
                  children: [
                    Text(
                      _selectedPeriod == 'year'
                          ? '年度收支趋势图'
                          : _selectedPeriod == 'month'
                          ? '月度收支趋势图'
                          : '日收支趋势图',
                      style: TextStyle(
                        fontSize: screenWidth * 0.04,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: screenHeight * 0.02),
                    Expanded(
                      child: ListView.builder(
                        itemCount:
                            data.length > 15 ? 15 : data.length, // 限制显示条数
                        itemBuilder: (context, index) {
                          final item = data[index];
                          double maxAmount = data.fold(0.0, (max, d) =>
                              [max, d.income, d.expense].reduce((a, b) => a > b ? a : b));

                          // 如果是日统计，高亮显示选中的日期
                          bool isSelectedDate = false;
                          if (_selectedPeriod == 'day') {
                            DateTime itemDate = _selectedDate.subtract(Duration(days: 7 - index));
                            isSelectedDate = itemDate.day == _selectedDate.day &&
                                itemDate.month == _selectedDate.month &&
                                itemDate.year == _selectedDate.year;
                          }

                          return Container(
                            margin: EdgeInsets.symmetric(
                              vertical: screenHeight * 0.005,
                            ),
                            padding: EdgeInsets.all(screenWidth * 0.02),
                            decoration: BoxDecoration(
                              color:
                                  isSelectedDate
                                      ? Colors.blue.withOpacity(0.1)
                                      : null,
                              borderRadius: BorderRadius.circular(8),
                              border:
                                  isSelectedDate
                                      ? Border.all(color: Colors.blue, width: 2)
                                      : null,
                            ),
                            child: Row(
                              children: [
                                SizedBox(
                                  width: screenWidth * 0.15,
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        item.period,
                                        style: TextStyle(
                                          fontSize: screenWidth * 0.03,
                                          fontWeight:
                                              isSelectedDate
                                                  ? FontWeight.bold
                                                  : FontWeight.normal,
                                          color:
                                              isSelectedDate
                                                  ? Colors.blue
                                                  : null,
                                        ),
                                      ),
                                      if (isSelectedDate)
                                        Text(
                                          '今日',
                                          style: TextStyle(
                                            fontSize: screenWidth * 0.025,
                                            color: Colors.blue,
                                          ),
                                        ),
                                    ],
                                  ),
                                ),
                                Expanded(
                                  child: Column(
                                    children: [
                                      // 收入条
                                      Row(
                                        children: [
                                          SizedBox(
                                            width: screenWidth * 0.1,
                                            child: Text(
                                              '收入',
                                              style: TextStyle(
                                                fontSize: screenWidth * 0.025,
                                                color: Colors.green,
                                              ),
                                            ),
                                          ),
                                          Expanded(
                                            child: SizedBox(
                                              height: screenHeight * 0.015,
                                              child: LinearProgressIndicator(
                                                value:
                                                    maxAmount > 0
                                                        ? item.income /
                                                            maxAmount
                                                        : 0,
                                                backgroundColor:
                                                    Colors.grey[200],
                                                valueColor:
                                                    const AlwaysStoppedAnimation<
                                                      Color
                                                    >(Colors.green),
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                            width: screenWidth * 0.15,
                                            child: Text(
                                              '¥${item.income.toInt()}',
                                              style: TextStyle(
                                                fontSize: screenWidth * 0.025,
                                                color: Colors.green,
                                              ),
                                              textAlign: TextAlign.end,
                                            ),
                                          ),
                                        ],
                                      ),
                                      SizedBox(height: screenHeight * 0.005),
                                      // 支出条
                                      Row(
                                        children: [
                                          SizedBox(
                                            width: screenWidth * 0.1,
                                            child: Text(
                                              '支出',
                                              style: TextStyle(
                                                fontSize: screenWidth * 0.025,
                                                color: Colors.red,
                                              ),
                                            ),
                                          ),
                                          Expanded(
                                            child: SizedBox(
                                              height: screenHeight * 0.015,
                                              child: LinearProgressIndicator(
                                                value:
                                                    maxAmount > 0
                                                        ? item.expense /
                                                            maxAmount
                                                        : 0,
                                                backgroundColor:
                                                    Colors.grey[200],
                                                valueColor:
                                                    const AlwaysStoppedAnimation<
                                                      Color
                                                    >(Colors.red),
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                            width: screenWidth * 0.15,
                                            child: Text(
                                              '¥${item.expense.toInt()}',
                                              style: TextStyle(
                                                fontSize: screenWidth * 0.025,
                                                color: Colors.red,
                                              ),
                                              textAlign: TextAlign.end,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 分类统计
  Widget _buildCategoryStatistics() {
    DateTime? startDate, endDate;

    switch (_selectedPeriod) {
      case 'year':
        startDate = DateTime(_selectedYear, 1, 1);
        endDate = DateTime(_selectedYear, 12, 31);
        break;
      case 'month':
        startDate = DateTime(_selectedYear, _selectedMonth, 1);
        endDate = DateTime(_selectedYear, _selectedMonth + 1, 0);
        break;
      case 'day':
      // 对于日统计，显示选中日期的数据
        startDate = DateTime(_selectedDate.year, _selectedDate.month, _selectedDate.day);
        endDate = startDate.add(const Duration(hours: 23, minutes: 59, seconds: 59));
        break;
    }

    return DefaultTabController(
      length: 2,
      child: Column(
        children: [
          // 时间范围显示
          if (_selectedPeriod == 'day')
            Container(
              padding: EdgeInsets.all(screenWidth * 0.04),
              child: Text(
                '统计日期：${DateFormat('yyyy年MM月dd日').format(_selectedDate)}',
                style: TextStyle(
                  fontSize: screenWidth * 0.035,
                  color: Colors.grey[600],
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          TabBar(
            labelColor: Colors.blue,
            unselectedLabelColor: Colors.grey,
            labelStyle: TextStyle(fontSize: screenWidth * 0.035),
            tabs: const [Tab(text: '支出分类'), Tab(text: '收入分类')],
          ),
          Expanded(
            child: TabBarView(
              children: [
                _buildCategoryChart('expense', startDate, endDate),
                _buildCategoryChart('income', startDate, endDate),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCategoryChart(String type, DateTime? startDate, DateTime? endDate) {

    List<CategoryData> categoryData = DataStorage().getCategoryStatistics(type, startDate, endDate);

    if (categoryData.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.pie_chart, size: screenWidth * 0.15, color: Colors.grey),
            SizedBox(height: screenHeight * 0.02),
            Text(
              '暂无${type == 'expense' ? '支出' : '收入'}数据',
              style: TextStyle(
                fontSize: screenWidth * 0.04,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    double total = categoryData.fold(0.0, (sum, data) => sum + data.amount);

    return Padding(
      padding: EdgeInsets.all(screenWidth * 0.04),
      child: Column(
        children: [
          // 总计显示
          Card(
            child: Padding(
              padding: EdgeInsets.all(screenWidth * 0.04),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '总${type == 'expense' ? '支出' : '收入'}：',
                    style: TextStyle(
                      fontSize: screenWidth * 0.04,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    '¥${total.toStringAsFixed(2)}',
                    style: TextStyle(
                      fontSize: screenWidth * 0.045,
                      fontWeight: FontWeight.bold,
                      color: type == 'expense' ? Colors.red : Colors.green,
                    ),
                  ),
                ],
              ),
            ),
          ),

          SizedBox(height: screenHeight * 0.02),

          // 分类列表
          Expanded(
            child: ListView.builder(
              itemCount: categoryData.length,
              itemBuilder: (context, index) {
                final data = categoryData[index];
                double percentage = total > 0 ? (data.amount / total) * 100 : 0;

                return Card(
                  margin: EdgeInsets.symmetric(vertical: screenHeight * 0.005),
                  child: Padding(
                    padding: EdgeInsets.all(screenWidth * 0.04),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              data.categoryName,
                              style: TextStyle(
                                fontSize: screenWidth * 0.04,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Text(
                                  '¥${data.amount.toStringAsFixed(2)}',
                                  style: TextStyle(
                                    fontSize: screenWidth * 0.04,
                                    fontWeight: FontWeight.bold,
                                    color:
                                        type == 'expense'
                                            ? Colors.red
                                            : Colors.green,
                                  ),
                                ),
                                Text(
                                  '${percentage.toStringAsFixed(1)}%',
                                  style: TextStyle(
                                    fontSize: screenWidth * 0.032,
                                    color: Colors.grey,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                        SizedBox(height: screenHeight * 0.01),
                        LinearProgressIndicator(
                          value: percentage / 100,
                          backgroundColor: Colors.grey[200],
                          valueColor: AlwaysStoppedAnimation<Color>(
                            type == 'expense' ? Colors.red : Colors.green,
                          ),
                        ),
                        SizedBox(height: screenHeight * 0.005),
                        Text(
                          '${data.count} 笔交易',
                          style: TextStyle(
                            fontSize: screenWidth * 0.032,
                            color: Colors.grey,
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  // 饼图分析
  Widget _buildPieChartAnalysis() {
    DateTime? startDate, endDate;

    switch (_selectedPeriod) {
      case 'year':
        startDate = DateTime(_selectedYear, 1, 1);
        endDate = DateTime(_selectedYear, 12, 31);
        break;
      case 'month':
        startDate = DateTime(_selectedYear, _selectedMonth, 1);
        endDate = DateTime(_selectedYear, _selectedMonth + 1, 0);
        break;
      case 'day':
      // 对于日统计，显示选中日期的数据
        startDate = DateTime(_selectedDate.year, _selectedDate.month, _selectedDate.day);
        endDate = startDate.add(const Duration(hours: 23, minutes: 59, seconds: 59));
        break;
    }

    return DefaultTabController(
      length: 2,
      child: Column(
        children: [
          // 时间范围显示
          if (_selectedPeriod == 'day')
            Container(
              padding: EdgeInsets.all(screenWidth * 0.04),
              child: Text(
                '分析日期：${DateFormat('yyyy年MM月dd日').format(_selectedDate)}',
                style: TextStyle(
                  fontSize: screenWidth * 0.035,
                  color: Colors.grey[600],
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          TabBar(
            labelColor: Colors.blue,
            unselectedLabelColor: Colors.grey,
            labelStyle: TextStyle(fontSize: screenWidth * 0.035),
            tabs: const [Tab(text: '支出饼图'), Tab(text: '收入饼图')],
          ),
          Expanded(
            child: TabBarView(
              children: [
                _buildPieChart('expense', startDate, endDate),
                _buildPieChart('income', startDate, endDate),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建饼图
  Widget _buildPieChart(String type, DateTime? startDate, DateTime? endDate) {

    List<CategoryData> categoryData = DataStorage().getCategoryStatistics(type, startDate, endDate);

    if (categoryData.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.pie_chart, size: screenWidth * 0.15, color: Colors.grey),
            SizedBox(height: screenHeight * 0.02),
            Text(
              '暂无${type == 'expense' ? '支出' : '收入'}数据',
              style: TextStyle(
                fontSize: screenWidth * 0.04,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    double total = categoryData.fold(0.0, (sum, data) => sum + data.amount);

    // 定义颜色列表
    List<Color> colors = [
      Colors.red[400]!,
      Colors.orange[400]!,
      Colors.yellow[600]!,
      Colors.green[400]!,
      Colors.blue[400]!,
      Colors.purple[400]!,
      Colors.pink[400]!,
      Colors.teal[400]!,
      Colors.indigo[400]!,
      Colors.brown[400]!,
    ];

    return Padding(
      padding: EdgeInsets.all(screenWidth * 0.04),
      child: Column(
        children: [
          // 总计显示
          Card(
            child: Padding(
              padding: EdgeInsets.all(screenWidth * 0.04),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '总${type == 'expense' ? '支出' : '收入'}：',
                    style: TextStyle(
                      fontSize: screenWidth * 0.04,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    '¥${total.toStringAsFixed(2)}',
                    style: TextStyle(
                      fontSize: screenWidth * 0.045,
                      fontWeight: FontWeight.bold,
                      color: type == 'expense' ? Colors.red : Colors.green,
                    ),
                  ),
                ],
              ),
            ),
          ),

          SizedBox(height: screenHeight * 0.02),

          // 饼图区域
          Expanded(
            child: Card(
              child: Padding(
                padding: EdgeInsets.all(screenWidth * 0.04),
                child: Column(
                  children: [
                    Text(
                      '${type == 'expense' ? '支出' : '收入'}分布饼图',
                      style: TextStyle(
                        fontSize: screenWidth * 0.04,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: screenHeight * 0.02),

                    // 自制饼图
                    Expanded(
                      child: Row(
                        children: [
                          // 饼图部分
                          Expanded(
                            flex: 1,
                            child: SizedBox(
                              height: screenWidth * 0.6,
                              child: CustomPaint(
                                painter: PieChartPainter(
                                  categoryData: categoryData,
                                  total: total,
                                  colors: colors,
                                ),
                                child: Container(),
                              ),
                            ),
                          ),

                          SizedBox(width: screenWidth * 0.04),

                          // 图例部分
                          Expanded(
                            flex: 1,
                            child: ListView.builder(
                              itemCount: categoryData.length,
                              itemBuilder: (context, index) {
                                final data = categoryData[index];
                                double percentage =
                                    total > 0 ? (data.amount / total) * 100 : 0;
                                Color color = colors[index % colors.length];

                                return Container(
                                  margin: EdgeInsets.symmetric(
                                    vertical: screenHeight * 0.005,
                                  ),
                                  child: Row(
                                    children: [
                                      Container(
                                        width: screenWidth * 0.04,
                                        height: screenWidth * 0.04,
                                        decoration: BoxDecoration(
                                          color: color,
                                          shape: BoxShape.circle,
                                        ),
                                      ),
                                      SizedBox(width: screenWidth * 0.02),
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              data.categoryName,
                                              style: TextStyle(
                                                fontSize: screenWidth * 0.032,
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                            Text(
                                              '${percentage.toStringAsFixed(1)}%',
                                              style: TextStyle(
                                                fontSize: screenWidth * 0.028,
                                                color: Colors.grey,
                                              ),
                                            ),
                                            Text(
                                              '¥${data.amount.toStringAsFixed(0)}',
                                              style: TextStyle(
                                                fontSize: screenWidth * 0.03,
                                                color:
                                                    type == 'expense'
                                                        ? Colors.red
                                                        : Colors.green,
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),

                    SizedBox(height: screenHeight * 0.02),

                    // 详细统计信息
                    Container(
                      padding: EdgeInsets.all(screenWidth * 0.03),
                      decoration: BoxDecoration(
                        color: Colors.grey[100],
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Column(
                            children: [
                              Text(
                                '分类数量',
                                style: TextStyle(
                                  fontSize: screenWidth * 0.032,
                                  color: Colors.grey[600],
                                ),
                              ),
                              Text(
                                '${categoryData.length}',
                                style: TextStyle(
                                  fontSize: screenWidth * 0.04,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.blue,
                                ),
                              ),
                            ],
                          ),
                          Column(
                            children: [
                              Text(
                                '交易笔数',
                                style: TextStyle(
                                  fontSize: screenWidth * 0.032,
                                  color: Colors.grey[600],
                                ),
                              ),
                              Text(
                                '${categoryData.fold(0, (sum, data) => sum + data.count)}',
                                style: TextStyle(
                                  fontSize: screenWidth * 0.04,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.blue,
                                ),
                              ),
                            ],
                          ),
                          Column(
                            children: [
                              Text(
                                '平均金额',
                                style: TextStyle(
                                  fontSize: screenWidth * 0.032,
                                  color: Colors.grey[600],
                                ),
                              ),
                              Text(
                                '¥${categoryData.isNotEmpty ? (total / categoryData.fold(0, (sum, data) => sum + data.count)).toStringAsFixed(0) : '0'}',
                                style: TextStyle(
                                  fontSize: screenWidth * 0.04,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.blue,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// 我的页面
class ProfilePage extends StatelessWidget {
  const ProfilePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: screenWidth * 0.3,
            height: screenWidth * 0.3,
            decoration: BoxDecoration(
              color: Colors.blue[100],
              borderRadius: BorderRadius.circular(screenWidth * 0.15),
            ),
            child: Icon(
              Icons.person,
              size: screenWidth * 0.15,
              color: Colors.blue,
            ),
          ),
          SizedBox(height: screenHeight * 0.03),
          Text(
            '用户中心',
            style: TextStyle(
              fontSize: screenWidth * 0.06,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: screenHeight * 0.015),
          Text(
            _currentUsername,
            style: TextStyle(fontSize: screenWidth * 0.04, color: Colors.grey),
          ),
          SizedBox(height: screenHeight * 0.06),
          _buildProfileButton(context, '账户管理', const AccountManagementPage()),
          SizedBox(height: screenHeight * 0.02),
          _buildProfileButton(context, '预算管理', const BudgetManagementPage()),
          SizedBox(height: screenHeight * 0.02),
          _buildProfileButton(context, '数据备份', const DataBackupPage()),
          SizedBox(height: screenHeight * 0.02),
          _buildProfileButton(context, '设置', const SettingsPage()),
        ],
      ),
    );
  }

  Widget _buildProfileButton(BuildContext context, String text, Widget page) {
    return SizedBox(
      width: screenWidth * 0.6,
      height: screenHeight * 0.06,
      child: ElevatedButton(
        onPressed: () {
          Navigator.of(
            context,
          ).push(MaterialPageRoute(builder: (context) => page));
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.blue,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25),
          ),
        ),
        child: Text(
          text,
          style: TextStyle(fontSize: screenWidth * 0.04, color: Colors.white),
        ),
      ),
    );
  }
}

// 账户管理页面（扩展版）
class AccountManagementPage extends StatefulWidget {
  const AccountManagementPage({Key? key}) : super(key: key);

  @override
  _AccountManagementPageState createState() => _AccountManagementPageState();
}

class _AccountManagementPageState extends State<AccountManagementPage> {
  final TextEditingController _currentPasswordController =
      TextEditingController();
  final TextEditingController _newPasswordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();
  final TextEditingController _newUsernameController = TextEditingController();

  bool _obscureCurrentPassword = true;
  bool _obscureNewPassword = true;
  bool _obscureConfirmPassword = true;



  @override
  void dispose() {
    _currentPasswordController.dispose();
    _newPasswordController.dispose();
    _confirmPasswordController.dispose();
    _newUsernameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('账户管理', style: TextStyle(fontSize: screenWidth * 0.045)),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(screenWidth * 0.04),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 当前用户信息
            Card(
              elevation: 2,
              child: Padding(
                padding: EdgeInsets.all(screenWidth * 0.04),
                child: Row(
                  children: [
                    Icon(
                      Icons.person,
                      size: screenWidth * 0.08,
                      color: Colors.blue,
                    ),
                    SizedBox(width: screenWidth * 0.04),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '当前用户名',
                          style: TextStyle(
                            fontSize: screenWidth * 0.035,
                            color: Colors.grey,
                          ),
                        ),
                        Text(
                          _currentUsername,
                          style: TextStyle(
                            fontSize: screenWidth * 0.04,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: screenHeight * 0.03),

            // 修改用户名部分
            Text(
              '修改用户名',
              style: TextStyle(
                fontSize: screenWidth * 0.045,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: screenHeight * 0.02),
            TextFormField(
              controller: _newUsernameController,
              style: TextStyle(fontSize: screenWidth * 0.04),
              decoration: InputDecoration(
                labelText: '新用户名',
                labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                border: const OutlineInputBorder(),
                prefixIcon: const Icon(Icons.email),
                contentPadding: EdgeInsets.symmetric(
                  horizontal: screenWidth * 0.04,
                  vertical: screenHeight * 0.02,
                ),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入新用户名';
                }
                if (!RegExp(
                  r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$',
                ).hasMatch(value)) {
                  return '请输入有效的邮箱地址';
                }
                return null;
              },
            ),
            SizedBox(height: screenHeight * 0.02),
            SizedBox(
              width: double.infinity,
              height: screenHeight * 0.06,
              child: ElevatedButton(
                onPressed: _changeUsername,
                style: ElevatedButton.styleFrom(backgroundColor: Colors.blue),
                child: Text(
                  '更新用户名',
                  style: TextStyle(
                    fontSize: screenWidth * 0.04,
                    color: Colors.white,
                  ),
                ),
              ),
            ),

            SizedBox(height: screenHeight * 0.04),

            // 修改密码部分
            Text(
              '修改密码',
              style: TextStyle(
                fontSize: screenWidth * 0.045,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: screenHeight * 0.02),
            TextFormField(
              controller: _currentPasswordController,
              obscureText: _obscureCurrentPassword,
              style: TextStyle(fontSize: screenWidth * 0.04),
              decoration: InputDecoration(
                labelText: '当前密码',
                labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                border: const OutlineInputBorder(),
                prefixIcon: const Icon(Icons.lock),
                suffixIcon: IconButton(
                  icon: Icon(
                    _obscureCurrentPassword
                        ? Icons.visibility
                        : Icons.visibility_off,
                  ),
                  onPressed: () {
                    setState(() {
                      _obscureCurrentPassword = !_obscureCurrentPassword;
                    });
                  },
                ),
                contentPadding: EdgeInsets.symmetric(
                  horizontal: screenWidth * 0.04,
                  vertical: screenHeight * 0.02,
                ),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入当前密码';
                }
                return null;
              },
            ),
            SizedBox(height: screenHeight * 0.02),
            TextFormField(
              controller: _newPasswordController,
              obscureText: _obscureNewPassword,
              style: TextStyle(fontSize: screenWidth * 0.04),
              decoration: InputDecoration(
                labelText: '新密码',
                labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                border: const OutlineInputBorder(),
                prefixIcon: const Icon(Icons.lock_outline),
                suffixIcon: IconButton(
                  icon: Icon(
                    _obscureNewPassword
                        ? Icons.visibility
                        : Icons.visibility_off,
                  ),
                  onPressed: () {
                    setState(() {
                      _obscureNewPassword = !_obscureNewPassword;
                    });
                  },
                ),
                contentPadding: EdgeInsets.symmetric(
                  horizontal: screenWidth * 0.04,
                  vertical: screenHeight * 0.02,
                ),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入新密码';
                }
                if (value.length < 6) {
                  return '密码长度至少为6位';
                }
                return null;
              },
            ),
            SizedBox(height: screenHeight * 0.02),
            TextFormField(
              controller: _confirmPasswordController,
              obscureText: _obscureConfirmPassword,
              style: TextStyle(fontSize: screenWidth * 0.04),
              decoration: InputDecoration(
                labelText: '确认新密码',
                labelStyle: TextStyle(fontSize: screenWidth * 0.035),
                border: const OutlineInputBorder(),
                prefixIcon: const Icon(Icons.lock_reset),
                suffixIcon: IconButton(
                  icon: Icon(
                    _obscureConfirmPassword
                        ? Icons.visibility
                        : Icons.visibility_off,
                  ),
                  onPressed: () {
                    setState(() {
                      _obscureConfirmPassword = !_obscureConfirmPassword;
                    });
                  },
                ),
                contentPadding: EdgeInsets.symmetric(
                  horizontal: screenWidth * 0.04,
                  vertical: screenHeight * 0.02,
                ),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请确认新密码';
                }
                if (value != _newPasswordController.text) {
                  return '两次输入的密码不一致';
                }
                return null;
              },
            ),
            SizedBox(height: screenHeight * 0.02),
            SizedBox(
              width: double.infinity,
              height: screenHeight * 0.06,
              child: ElevatedButton(
                onPressed: _changePassword,
                style: ElevatedButton.styleFrom(backgroundColor: Colors.blue),
                child: Text(
                  '更新密码',
                  style: TextStyle(
                    fontSize: screenWidth * 0.04,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _changeUsername() {
    final newUsername = _newUsernameController.text.trim();

    if (newUsername.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('请输入新用户名')));
      return;
    }

    if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(newUsername)) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('请输入有效的邮箱地址')));
      return;
    }

    // 模拟更新用户名
    setState(() {
      _currentUsername = newUsername;
    });

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('用户名已更新为: $newUsername'),
        backgroundColor: Colors.green,
      ),
    );

    // 清空输入框
    _newUsernameController.clear();
  }

  void _changePassword() {
    final currentPassword = _currentPasswordController.text;
    final newPassword = _newPasswordController.text;
    final confirmPassword = _confirmPasswordController.text;

    if (currentPassword.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('请输入当前密码')));
      return;
    }

    if (newPassword.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('请输入新密码')));
      return;
    }

    if (newPassword.length < 6) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('密码长度至少为6位')));
      return;
    }

    if (newPassword != confirmPassword) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('两次输入的密码不一致')));
      return;
    }

    // 模拟验证当前密码（实际应用中需要与后端验证）
    if (currentPassword != 'password') {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('当前密码不正确')));
      return;
    }

    // 模拟更新密码
    setState(() {
      password = newPassword;
    });

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: const Text('密码已更新'), backgroundColor: Colors.green),
    );

    // 清空输入框
    _currentPasswordController.clear();
    _newPasswordController.clear();
    _confirmPasswordController.clear();
  }
}

// 预算管理页面
class BudgetManagementPage extends StatefulWidget {
  const BudgetManagementPage({super.key});

  @override
  State<BudgetManagementPage> createState() => _BudgetManagementPageState();
}

class _BudgetManagementPageState extends State<BudgetManagementPage> {
  @override
  Widget build(BuildContext context) {
    List<BudgetUsage> budgetUsages = DataStorage().getBudgetUsages();

    return Scaffold(
      appBar: AppBar(
        title: Text(
          '预算管理',
          style: TextStyle(fontSize: screenWidth * 0.045),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const AddBudgetPage(),
                ),
              ).then((_) => setState(() {}));
            },
          ),
        ],
      ),
      body: budgetUsages.isEmpty
          ? _buildEmptyState()
          : ListView(
              padding: EdgeInsets.all(screenWidth * 0.04),
              children: [
                // 预算概览卡片
                _buildBudgetOverviewCard(budgetUsages),
                SizedBox(height: screenHeight * 0.02),

                // 预算列表
                Text(
                  '预算详情',
                  style: TextStyle(
                    fontSize: screenWidth * 0.045,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: screenHeight * 0.01),

                ...budgetUsages.map((usage) => _buildBudgetCard(usage)),
              ],
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const AddBudgetPage(),
            ),
          ).then((_) => setState(() {}));
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.account_balance_wallet_outlined,
            size: screenWidth * 0.2,
            color: Colors.grey[400],
          ),
          SizedBox(height: screenHeight * 0.02),
          Text(
            '还没有设置预算',
            style: TextStyle(
              fontSize: screenWidth * 0.05,
              fontWeight: FontWeight.bold,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(height: screenHeight * 0.01),
          Text(
            '点击右上角的 + 号开始设置您的第一个预算',
            style: TextStyle(
              fontSize: screenWidth * 0.035,
              color: Colors.grey[500],
            ),
            textAlign: TextAlign.center,
          ),
          SizedBox(height: screenHeight * 0.04),
          ElevatedButton.icon(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const AddBudgetPage(),
                ),
              ).then((_) => setState(() {}));
            },
            icon: const Icon(Icons.add),
            label: const Text('添加预算'),
          ),
        ],
      ),
    );
  }

  Widget _buildBudgetOverviewCard(List<BudgetUsage> budgetUsages) {
    double totalBudget = budgetUsages.fold(0.0, (sum, usage) => sum + usage.budget.amount);
    double totalUsed = budgetUsages.fold(0.0, (sum, usage) => sum + usage.usedAmount);
    double totalRemaining = totalBudget - totalUsed;
    double overallPercentage = totalBudget > 0 ? (totalUsed / totalBudget) * 100 : 0;

    return Card(
      elevation: 4,
      child: Padding(
        padding: EdgeInsets.all(screenWidth * 0.04),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '预算概览',
              style: TextStyle(
                fontSize: screenWidth * 0.045,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: screenHeight * 0.02),

            Row(
              children: [
                Expanded(
                  child: _buildOverviewItem('总预算', totalBudget, Colors.blue),
                ),
                Expanded(
                  child: _buildOverviewItem('已使用', totalUsed, Colors.orange),
                ),
                Expanded(
                  child: _buildOverviewItem('剩余', totalRemaining, Colors.green),
                ),
              ],
            ),

            SizedBox(height: screenHeight * 0.02),

            // 总体进度条
            Text(
              '总体使用率: ${overallPercentage.toStringAsFixed(1)}%',
              style: TextStyle(
                fontSize: screenWidth * 0.035,
                color: Colors.grey[600],
              ),
            ),
            SizedBox(height: screenHeight * 0.01),
            LinearProgressIndicator(
              value: overallPercentage / 100,
              backgroundColor: Colors.grey[300],
              valueColor: AlwaysStoppedAnimation<Color>(
                overallPercentage > 100 ? Colors.red :
                overallPercentage > 80 ? Colors.orange : Colors.green,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildOverviewItem(String title, double amount, Color color) {
    return Column(
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: screenWidth * 0.032,
            color: Colors.grey[600],
          ),
        ),
        SizedBox(height: screenHeight * 0.005),
        Text(
          '¥${amount.toStringAsFixed(0)}',
          style: TextStyle(
            fontSize: screenWidth * 0.04,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
      ],
    );
  }

  Widget _buildBudgetCard(BudgetUsage usage) {
    Color progressColor = usage.percentage > 100 ? Colors.red :
                         usage.percentage > 80 ? Colors.orange : Colors.green;

    return Card(
      margin: EdgeInsets.only(bottom: screenHeight * 0.015),
      child: Padding(
        padding: EdgeInsets.all(screenWidth * 0.04),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  usage.budget.categoryName,
                  style: TextStyle(
                    fontSize: screenWidth * 0.04,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                PopupMenuButton<String>(
                  onSelected: (value) {
                    if (value == 'edit') {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => EditBudgetPage(budget: usage.budget),
                        ),
                      ).then((_) => setState(() {}));
                    } else if (value == 'delete') {
                      _showDeleteConfirmDialog(usage.budget);
                    }
                  },
                  itemBuilder: (context) => [
                    const PopupMenuItem(
                      value: 'edit',
                      child: Text('编辑'),
                    ),
                    const PopupMenuItem(
                      value: 'delete',
                      child: Text('删除'),
                    ),
                  ],
                ),
              ],
            ),

            SizedBox(height: screenHeight * 0.01),

            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '已用: ¥${usage.usedAmount.toStringAsFixed(0)}',
                  style: TextStyle(
                    fontSize: screenWidth * 0.035,
                    color: Colors.grey[600],
                  ),
                ),
                Text(
                  '预算: ¥${usage.budget.amount.toStringAsFixed(0)}',
                  style: TextStyle(
                    fontSize: screenWidth * 0.035,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),

            SizedBox(height: screenHeight * 0.01),

            LinearProgressIndicator(
              value: usage.percentage / 100,
              backgroundColor: Colors.grey[300],
              valueColor: AlwaysStoppedAnimation<Color>(progressColor),
            ),

            SizedBox(height: screenHeight * 0.01),

            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '${usage.percentage.toStringAsFixed(1)}%',
                  style: TextStyle(
                    fontSize: screenWidth * 0.035,
                    color: progressColor,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  usage.percentage > 100
                      ? '超支 ¥${(-usage.remainingAmount).toStringAsFixed(0)}'
                      : '剩余 ¥${usage.remainingAmount.toStringAsFixed(0)}',
                  style: TextStyle(
                    fontSize: screenWidth * 0.035,
                    color: usage.percentage > 100 ? Colors.red : Colors.green,
                  ),
                ),
              ],
            ),

            if (usage.relatedRecords.isNotEmpty) ...[
              SizedBox(height: screenHeight * 0.01),
              Text(
                '本期消费 ${usage.relatedRecords.length} 笔',
                style: TextStyle(
                  fontSize: screenWidth * 0.03,
                  color: Colors.grey[500],
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  void _showDeleteConfirmDialog(Budget budget) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除"${budget.categoryName}"的预算设置吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              DataStorage().removeBudget(budget.id);
              Navigator.pop(context);
              setState(() {});
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('预算已删除')),
              );
            },
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }
}

//数据备份页面
class DataBackupPage extends StatefulWidget {
  const DataBackupPage({Key? key}) : super(key: key);

  @override
  _DataBackupPageState createState() => _DataBackupPageState();
}

class _DataBackupPageState extends State<DataBackupPage> {
  bool _isBackingUp = false;
  bool _isRestoring = false;

  Future<void> _performBackup() async {
    setState(() => _isBackingUp = true);
    await Future.delayed(const Duration(seconds: 1)); // 模拟备份过程
    
    // 使用 DataStorage 存储备份数据
    DataStorage().backupData();

    setState(() => _isBackingUp = false);
    
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('数据备份成功！'),
        backgroundColor: Colors.green,
      ),
    );
  }

  Future<void> _restoreData() async {
    // 从 DataStorage 获取备份数据
    final backupData = DataStorage().backupDataString;
    if (backupData == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请先备份数据'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    setState(() => _isRestoring = true);
    await Future.delayed(const Duration(seconds: 1)); // 模拟恢复过程
    
    try {
      DataStorage().restoreData(backupData!);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('数据恢复成功！'),
          backgroundColor: Colors.green,
        ),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('恢复失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
    
    setState(() => _isRestoring = false);
  }

  @override
  Widget build(BuildContext context) {
    // 从 DataStorage 获取备份状态
    final backupData = DataStorage().backupDataString;
    return Scaffold(
      appBar: AppBar(
        title: Text('数据备份', style: TextStyle(fontSize: screenWidth * 0.045)),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: Padding(
        padding: EdgeInsets.all(screenWidth * 0.04),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 备份状态显示
            Card(
              child: Padding(
                padding: EdgeInsets.all(screenWidth * 0.04),
                child: Column(
                  children: [
                    const Icon(Icons.backup, size: 48, color: Colors.blue),
                    SizedBox(height: screenHeight * 0.02),
                    Text(
                      // 使用从 DataStorage 获取的数据
                      backupData != null  
                        ? '最后备份: ${DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now())}'
                        : '尚未备份数据',
                      style: TextStyle(fontSize: screenWidth * 0.04),
                    ),
                    if (backupData != null) ...[
                      SizedBox(height: screenHeight * 0.01),
                      Text(
                        '包含 ${DataStorage().records.length} 条记录',
                        style: TextStyle(
                          fontSize: screenWidth * 0.035,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            ),
            
            SizedBox(height: screenHeight * 0.04),
            
            // 备份按钮
            SizedBox(
              width: double.infinity,
              height: screenHeight * 0.06,
              child: ElevatedButton.icon(
                onPressed: _isBackingUp ? null : _performBackup,
                icon: _isBackingUp
                    ? const SizedBox(
                        width: 24,
                        height: 24,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          color: Colors.white,
                        ),
                      )
                    : const Icon(Icons.backup, color: Colors.white),
                label: Text(
                  _isBackingUp ? '备份中...' : '备份数据',
                  style: TextStyle(
                    fontSize: screenWidth * 0.04,
                    color: Colors.white,
                  ),
                ),
                style: ElevatedButton.styleFrom(backgroundColor: Colors.blue),
              ),
            ),
            
            SizedBox(height: screenHeight * 0.02),
            
            // 恢复按钮
            SizedBox(
              width: double.infinity,
              height: screenHeight * 0.06,
              child: ElevatedButton.icon(
                onPressed: _isRestoring || _performBackup == null ? null : _restoreData,
                icon: _isRestoring
                    ? const SizedBox(
                        width: 24,
                        height: 24,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          color: Colors.white,
                        ),
                      )
                    : const Icon(Icons.restore, color: Colors.white),
                label: Text(
                  _isRestoring ? '恢复中...' : '恢复数据',
                  style: TextStyle(
                    fontSize: screenWidth * 0.04,
                    color: Colors.white,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: backupData == null ? Colors.grey : Colors.green,
                ),
              ),
            ),
            
            SizedBox(height: screenHeight * 0.02),
            
            // 说明文本
            Padding(
              padding: EdgeInsets.symmetric(vertical: screenHeight * 0.02),
              child: Text(
                '备份数据包含所有账单记录和预算设置',
                style: TextStyle(
                  fontSize: screenWidth * 0.035,
                  color: Colors.grey,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class SettingsPage extends StatelessWidget {
  const SettingsPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('设置', style: TextStyle(fontSize: screenWidth * 0.045)),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: ListView(
        padding: EdgeInsets.all(screenWidth * 0.04),
        children: [
          _buildSettingsItem(
            context,
            '主题设置',
            Icons.color_lens,
            () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const ThemeSettingsPage()),
              );
            },
          ),
          _buildSettingsItem(
            context,
            '通知设置',
            Icons.notifications,
            () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const NotificationSettingsPage()),
              );
            },
          ),
          _buildSettingsItem(
            context,
            '隐私设置',
            Icons.privacy_tip,
            () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const PrivacySettingsPage()),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildSettingsItem(BuildContext context, String title, IconData icon, VoidCallback onTap) {
    return Card(
      margin: EdgeInsets.only(bottom: screenHeight * 0.015),
      child: ListTile(
        leading: Icon(icon, color: Colors.blue),
        title: Text(
          title,
          style: TextStyle(fontSize: screenWidth * 0.04),
        ),
        trailing: const Icon(Icons.arrow_forward_ios, size: 16),
        onTap: onTap,
      ),
    );
  }
}

// 主题设置页面
class ThemeSettingsPage extends StatelessWidget {
  const ThemeSettingsPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '主题设置',
          style: TextStyle(fontSize: screenWidth * 0.045),
        ),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: ListView(
        padding: EdgeInsets.all(screenWidth * 0.04),
        children: [
          _buildThemeOption(context, '浅色主题', ThemeMode.light),
          _buildThemeOption(context, '深色主题', ThemeMode.dark),
          _buildThemeOption(context, '跟随系统', ThemeMode.system),
        ],
      ),
    );
  }

  Widget _buildThemeOption(BuildContext context, String title, ThemeMode mode) {
    return Card(
      margin: EdgeInsets.only(bottom: screenHeight * 0.015),
      child: ListTile(
        title: Text(title, style: TextStyle(fontSize: screenWidth * 0.04)),
        trailing: ValueListenableBuilder<ThemeMode>(
          valueListenable: themeNotifier,
          builder: (_, currentMode, __) {
            return Radio<ThemeMode>(
              value: mode,
              groupValue: currentMode,
              onChanged: (ThemeMode? value) {
                if (value != null) {
                  themeNotifier.value = value;
                }
              },
            );
          },
        ),
        onTap: () {
          themeNotifier.value = mode;
        },
      ),
    );
  }
}

// 通知设置页面
class NotificationSettingsPage extends StatefulWidget {
  const NotificationSettingsPage({Key? key}) : super(key: key);

  @override
  _NotificationSettingsPageState createState() => _NotificationSettingsPageState();
}

class _NotificationSettingsPageState extends State<NotificationSettingsPage> {
  bool _notificationsEnabled = true;
  String _reminderMethod = '应用内通知'; // 默认提醒方式

  final List<String> _reminderMethods = ['应用内通知', '短信通知', '邮件通知'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '通知设置',
          style: TextStyle(fontSize: screenWidth * 0.045),
        ),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: ListView(
        padding: EdgeInsets.all(screenWidth * 0.04),
        children: [
          Card(
            margin: EdgeInsets.only(bottom: screenHeight * 0.015),
            child: SwitchListTile(
              title: Text(
                '允许通知',
                style: TextStyle(fontSize: screenWidth * 0.04),
              ),
              value: _notificationsEnabled,
              onChanged: (value) {
                setState(() {
                  _notificationsEnabled = value;
                });
              },
            ),
          ),
          if (_notificationsEnabled) ...[
            Card(
              margin: EdgeInsets.only(bottom: screenHeight * 0.015),
              child: Padding(
                padding: EdgeInsets.all(screenWidth * 0.04),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '提醒方式',
                      style: TextStyle(
                        fontSize: screenWidth * 0.04,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    ..._reminderMethods.map((method) {
                      return RadioListTile<String>(
                        title: Text(method),
                        value: method,
                        groupValue: _reminderMethod,
                        onChanged: (value) {
                          setState(() {
                            _reminderMethod = value!;
                          });
                        },
                      );
                    }).toList(),
                  ],
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }
}

// 隐私设置页面
class PrivacySettingsPage extends StatelessWidget {
  const PrivacySettingsPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '隐私设置',
          style: TextStyle(fontSize: screenWidth * 0.045),
        ),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: ListView(
        padding: EdgeInsets.all(screenWidth * 0.04),
        children: [
          Card(
            margin: EdgeInsets.only(bottom: screenHeight * 0.015),
            child: ListTile(
              title: Text(
                '隐私政策',
                style: TextStyle(fontSize: screenWidth * 0.04),
              ),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                // 跳转到隐私政策页面
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('隐私政策页面')),
                );
              },
            ),
          ),
          Card(
            margin: EdgeInsets.only(bottom: screenHeight * 0.015),
            child: ListTile(
              title: Text(
                '数据安全',
                style: TextStyle(fontSize: screenWidth * 0.04),
              ),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('数据安全页面')),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

// 自定义饼图绘制类
class PieChartPainter extends CustomPainter {
  final List<CategoryData> categoryData;
  final double total;
  final List<Color> colors;

  PieChartPainter({
    required this.categoryData,
    required this.total,
    required this.colors,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (categoryData.isEmpty || total == 0) return;

    final center = Offset(size.width / 2, size.height / 2);
    final radius = math.min(size.width, size.height) / 2 * 0.8;

    double startAngle = -math.pi / 2; // 从顶部开始

    for (int i = 0; i < categoryData.length; i++) {
      final data = categoryData[i];
      final sweepAngle = (data.amount / total) * 2 * math.pi;

      final paint = Paint()
        ..color = colors[i % colors.length]
        ..style = PaintingStyle.fill;

      // 绘制扇形
      canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        startAngle,
        sweepAngle,
        true,
        paint,
      );

      // 绘制边框
      final borderPaint =
          Paint()
            ..color = Colors.white
            ..style = PaintingStyle.stroke
            ..strokeWidth = 2;

      canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        startAngle,
        sweepAngle,
        true,
        borderPaint,
      );

      // 绘制百分比文字（如果扇形足够大）
      if (sweepAngle > 0.3) {
        // 只在扇形足够大时显示文字
        final percentage = (data.amount / total * 100);
        final textAngle = startAngle + sweepAngle / 2;
        final textRadius = radius * 0.7;
        final textX = center.dx + textRadius * math.cos(textAngle);
        final textY = center.dy + textRadius * math.sin(textAngle);

        final textSpan = TextSpan(
          text: '${percentage.toStringAsFixed(1)}%',
          style: TextStyle(
            color: Colors.white,
            fontSize: 12,
            fontWeight: FontWeight.bold,
            shadows: [
              Shadow(
                offset: const Offset(0.5, 0.5),
                blurRadius: 1,
                color: Colors.black.withOpacity(0.8),
              ),
            ],
          ),
        );

        final textPainter = TextPainter(
          text: textSpan,
          textDirection: ui.TextDirection.ltr, // 修复：使用 ui.TextDirection.ltr
        );

        textPainter.layout();

        final textOffset = Offset(
          textX - textPainter.width / 2,
          textY - textPainter.height / 2,
        );

        textPainter.paint(canvas, textOffset);
      }

      startAngle += sweepAngle;
    }

    // 绘制中心圆
    final centerPaint =
        Paint()
          ..color = Colors.white
          ..style = PaintingStyle.fill;

    canvas.drawCircle(center, radius * 0.3, centerPaint);

    // 绘制中心文字
    final centerTextSpan = TextSpan(
      text: '总计\n¥${total.toStringAsFixed(0)}',
      style: const TextStyle(
        color: Colors.black87,
        fontSize: 14,
        fontWeight: FontWeight.bold,
      ),
    );

    final centerTextPainter = TextPainter(
      text: centerTextSpan,
      textDirection: ui.TextDirection.ltr, // 修复：使用 ui.TextDirection.ltr
      textAlign: TextAlign.center,
    );

    centerTextPainter.layout();

    final centerTextOffset = Offset(
      center.dx - centerTextPainter.width / 2,
      center.dy - centerTextPainter.height / 2,
    );

    centerTextPainter.paint(canvas, centerTextOffset);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

// 预算页面
class AddBudgetPage extends StatefulWidget {
  const AddBudgetPage({super.key});

  @override
  State<AddBudgetPage> createState() => _AddBudgetPageState();
}

class _AddBudgetPageState extends State<AddBudgetPage> {
  final _formKey = GlobalKey<FormState>();
  final _amountController = TextEditingController();

  String _selectedCategory = 'food';
  String _selectedPeriod = 'monthly';

  final List<Map<String, String>> _categories = [
    {'id': 'food', 'name': '日常饮食'},
    {'id': 'transport', 'name': '交通出行'},
    {'id': 'entertainment', 'name': '娱乐社交'},
    {'id': 'daily', 'name': '生活用品'},
    {'id': 'fixed', 'name': '固定支出'},
    {'id': 'family', 'name': '家庭支出'},
    {'id': 'other', 'name': '其他'},
  ];

  @override
  void dispose() {
    _amountController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('添加预算'),
        actions: [
          TextButton(
            onPressed: _saveBudget,
            child: const Text('保存'),
          ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: EdgeInsets.all(screenWidth * 0.04),
          children: [
            // 分类选择
            Text(
              '选择分类',
              style: TextStyle(
                fontSize: screenWidth * 0.04,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: screenHeight * 0.01),
            DropdownButtonFormField<String>(
              value: _selectedCategory,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
              items: _categories.map((category) {
                return DropdownMenuItem<String>(
                  value: category['id'],
                  child: Text(category['name']!),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  _selectedCategory = value!;
                });
              },
            ),

            SizedBox(height: screenHeight * 0.03),

            // 预算金额
            Text(
              '预算金额',
              style: TextStyle(
                fontSize: screenWidth * 0.04,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: screenHeight * 0.01),
            TextFormField(
              controller: _amountController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                prefixText: '¥ ',
                hintText: '请输入预算金额',
                contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入预算金额';
                }
                if (double.tryParse(value) == null) {
                  return '请输入有效的金额';
                }
                if (double.parse(value) <= 0) {
                  return '预算金额必须大于0';
                }
                return null;
              },
            ),

            SizedBox(height: screenHeight * 0.03),

            // 预算周期
            Text(
              '预算周期',
              style: TextStyle(
                fontSize: screenWidth * 0.04,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: screenHeight * 0.01),
            DropdownButtonFormField<String>(
              value: _selectedPeriod,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
              items: const [
                DropdownMenuItem(value: 'monthly', child: Text('月度预算')),
                DropdownMenuItem(value: 'yearly', child: Text('年度预算')),
              ],
              onChanged: (value) {
                setState(() {
                  _selectedPeriod = value!;
                });
              },
            ),

            SizedBox(height: screenHeight * 0.04),

            // 保存按钮
            ElevatedButton(
              onPressed: _saveBudget,
              style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(vertical: screenHeight * 0.02),
              ),
              child: Text(
                '保存预算',
                style: TextStyle(fontSize: screenWidth * 0.04),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _saveBudget() {
    if (_formKey.currentState!.validate()) {
      final amount = double.parse(_amountController.text);
      final categoryName = _categories.firstWhere(
        (cat) => cat['id'] == _selectedCategory,
      )['name']!;

      DateTime now = DateTime.now();
      DateTime startDate, endDate;

      if (_selectedPeriod == 'monthly') {
        startDate = DateTime(now.year, now.month, 1);
        endDate = DateTime(now.year, now.month + 1, 0);
      } else {
        startDate = DateTime(now.year, 1, 1);
        endDate = DateTime(now.year, 12, 31);
      }

      final budget = Budget(
        id: 'budget_${DateTime.now().millisecondsSinceEpoch}',
        category: _selectedCategory,
        categoryName: categoryName,
        amount: amount,
        startDate: startDate,
        endDate: endDate,
        period: _selectedPeriod,
      );

      DataStorage().addBudget(budget);

      Navigator.pop(context);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('预算已保存')),
      );
    }
  }
}

// 编辑预算页面
class EditBudgetPage extends StatefulWidget {
  final Budget budget;

  const EditBudgetPage({super.key, required this.budget});

  @override
  State<EditBudgetPage> createState() => _EditBudgetPageState();
}

class _EditBudgetPageState extends State<EditBudgetPage> {
  final _formKey = GlobalKey<FormState>();
  final _amountController = TextEditingController();

  String _selectedCategory = '';
  String _selectedPeriod = '';

  final List<Map<String, String>> _categories = [
    {'id': 'food', 'name': '日常饮食'},
    {'id': 'transport', 'name': '交通出行'},
    {'id': 'entertainment', 'name': '娱乐社交'},
    {'id': 'daily', 'name': '生活用品'},
    {'id': 'fixed', 'name': '固定支出'},
    {'id': 'family', 'name': '家庭支出'},
    {'id': 'other', 'name': '其他'},
  ];

  @override
  void initState() {
    super.initState();
    _selectedCategory = widget.budget.category;
    _selectedPeriod = widget.budget.period;
    _amountController.text = widget.budget.amount.toString();
  }

  @override
  void dispose() {
    _amountController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('编辑预算'),
        actions: [
          TextButton(
            onPressed: _updateBudget,
            child: const Text('保存'),
          ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: EdgeInsets.all(screenWidth * 0.04),
          children: [
            // 分类选择
            Text(
              '选择分类',
              style: TextStyle(
                fontSize: screenWidth * 0.04,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: screenHeight * 0.01),
            DropdownButtonFormField<String>(
              value: _selectedCategory,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
              items: _categories.map((category) {
                return DropdownMenuItem<String>(
                  value: category['id'],
                  child: Text(category['name']!),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  _selectedCategory = value!;
                });
              },
            ),

            SizedBox(height: screenHeight * 0.03),

            // 预算金额
            Text(
              '预算金额',
              style: TextStyle(
                fontSize: screenWidth * 0.04,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: screenHeight * 0.01),
            TextFormField(
              controller: _amountController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                prefixText: '¥ ',
                hintText: '请输入预算金额',
                contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入预算金额';
                }
                if (double.tryParse(value) == null) {
                  return '请输入有效的金额';
                }
                if (double.parse(value) <= 0) {
                  return '预算金额必须大于0';
                }
                return null;
              },
            ),

            SizedBox(height: screenHeight * 0.03),

            // 预算周期
            Text(
              '预算周期',
              style: TextStyle(
                fontSize: screenWidth * 0.04,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: screenHeight * 0.01),
            DropdownButtonFormField<String>(
              value: _selectedPeriod,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
              items: const [
                DropdownMenuItem(value: 'monthly', child: Text('月度预算')),
                DropdownMenuItem(value: 'yearly', child: Text('年度预算')),
              ],
              onChanged: (value) {
                setState(() {
                  _selectedPeriod = value!;
                });
              },
            ),

            SizedBox(height: screenHeight * 0.04),

            // 更新按钮
            ElevatedButton(
              onPressed: _updateBudget,
              style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(vertical: screenHeight * 0.02),
              ),
              child: Text(
                '更新预算',
                style: TextStyle(fontSize: screenWidth * 0.04),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _updateBudget() {
    if (_formKey.currentState!.validate()) {
      final amount = double.parse(_amountController.text);
      final categoryName = _categories.firstWhere(
        (cat) => cat['id'] == _selectedCategory,
      )['name']!;

      DateTime now = DateTime.now();
      DateTime startDate, endDate;

      if (_selectedPeriod == 'monthly') {
        startDate = DateTime(now.year, now.month, 1);
        endDate = DateTime(now.year, now.month + 1, 0);
      } else {
        startDate = DateTime(now.year, 1, 1);
        endDate = DateTime(now.year, 12, 31);
      }

      final updatedBudget = Budget(
        id: widget.budget.id,
        category: _selectedCategory,
        categoryName: categoryName,
        amount: amount,
        startDate: startDate,
        endDate: endDate,
        period: _selectedPeriod,
      );

      DataStorage().updateBudget(updatedBudget);

      Navigator.pop(context);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('预算已更新')),
      );
    }
  }
}

class EditRecordPage extends StatefulWidget {
  final AccountRecord record;
  const EditRecordPage({Key? key, required this.record}) : super(key: key);

  @override
  _EditRecordPageState createState() => _EditRecordPageState();
}

class _EditRecordPageState extends State<EditRecordPage> {
  late TextEditingController _descriptionController;
  late TextEditingController _amountController;
  late DateTime _selectedDate;
  late String _selectedType; // 'expense' or 'income'
  late String _selectedCategory;

  final List<Map<String, String>> expenseCategories = [
    {'id': 'food', 'name': '日常饮食'},
    {'id': 'transport', 'name': '交通出行'},
    {'id': 'entertainment', 'name': '娱乐社交'},
    {'id': 'daily', 'name': '生活用品'},
    {'id': 'fixed', 'name': '固定支出'},
    {'id': 'family', 'name': '家庭支出'},
    {'id': 'other', 'name': '其他'},
  ];
  final List<Map<String, String>> incomeCategories = [
    {'id': 'salary', 'name': '工资'},
    {'id': 'parttime', 'name': '兼职'},
    {'id': 'other', 'name': '其他'},
  ];

  @override
  void initState() {
    super.initState();
    _descriptionController = TextEditingController(text: widget.record.description);
    _amountController = TextEditingController(text: widget.record.amount.toString());
    _selectedDate = widget.record.date;
    _selectedType = widget.record.type;
    _selectedCategory = widget.record.category;
  }

  @override
  void dispose() {
    _descriptionController.dispose();
    _amountController.dispose();
    super.dispose();
  }

  List<Map<String, String>> get _currentCategories =>
      _selectedType == 'expense' ? expenseCategories : incomeCategories;

  void _saveEdit() {
    if (_descriptionController.text.isNotEmpty && double.tryParse(_amountController.text) != null) {
      final updatedRecord = AccountRecord(
        id: widget.record.id,
        type: _selectedType,
        category: _selectedCategory,
        description: _descriptionController.text,
        amount: double.parse(_amountController.text),
        date: _selectedDate,
        method: widget.record.method,
      );
      DataStorage().updateRecord(updatedRecord);

      // 显示提示
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('账单已更新')),
      );

      Navigator.pop(context);
    }
  }

  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
    );
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('编辑账单')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: ListView(
          children: [
            // 收入/支出切换
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ChoiceChip(
                  label: Text('支出'),
                  selected: _selectedType == 'expense',
                  onSelected: (selected) {
                    if (selected) {
                      setState(() {
                        _selectedType = 'expense';
                        _selectedCategory = expenseCategories.first['id']!;
                      });
                    }
                  },
                ),
                SizedBox(width: 16),
                ChoiceChip(
                  label: Text('收入'),
                  selected: _selectedType == 'income',
                  onSelected: (selected) {
                    if (selected) {
                      setState(() {
                        _selectedType = 'income';
                        _selectedCategory = incomeCategories.first['id']!;
                      });
                    }
                  },
                ),
              ],
            ),
            SizedBox(height: 16),
            // 分类选择
            DropdownButtonFormField<String>(
              value: _selectedCategory,
              decoration: InputDecoration(labelText: '分类'),
              items: _currentCategories.map((cat) {
                return DropdownMenuItem<String>(
                  value: cat['id'],
                  child: Text(cat['name']!),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  _selectedCategory = value!;
                });
              },
            ),
            SizedBox(height: 16),
            // 备注
            TextFormField(
              controller: _descriptionController,
              decoration: InputDecoration(labelText: '备注'),
            ),
            SizedBox(height: 16),
            // 金额
            TextFormField(
              controller: _amountController,
              decoration: InputDecoration(labelText: '金额'),
              keyboardType: TextInputType.number,
            ),
            SizedBox(height: 16),
            // 日期选择
            Row(
              children: [
                Text('日期: ${_selectedDate.year}-${_selectedDate.month.toString().padLeft(2, '0')}-${_selectedDate.day.toString().padLeft(2, '0')}'),
                SizedBox(width: 16),
                ElevatedButton(
                  onPressed: _selectDate,
                  child: Text('选择日期'),
                ),
              ],
            ),
            SizedBox(height: 16),
            // 保存按钮
            ElevatedButton(
              onPressed: _saveEdit,
              child: Text('保存修改'),
            ),
          ],
        ),
      ),
    );
  }
}
